[% setvar title Exegesis 6: Subroutines %]
<div id="archive-notice">
    <h3>This file is part of the Perl 6 Archive</h3>
    <p>To see what is currently happening visit <a href="http://www.perl6.org/">http://www.perl6.org/</a></p>
</div>
<div class='pod'>
<a name='TITLE'></a><h1>TITLE</h1>
<p>Exegesis 6: Subroutines</p>
<a name='AUTHOR'></a><h1>AUTHOR</h1>
<p>Damian Conway &lt;<a href='mailto:damian@conway.org'>damian@conway.org</a>&gt;</p>
<a name='VERSION'></a><h1>VERSION</h1>
<pre>  Maintainer: Larry Wall &lt;<a href='mailto:larry@wall.org'>larry@wall.org</a>
  Date: 29 Jul 2003
  Last Modified: 29 May 2006
  Number: 6
  Version: 2</pre>
<p>[Update: Please note that this was written several years ago, and
a number of things have changed since then.  Rather than changing
the original document, we'll be inserting &quot;Update&quot; notes like this
one to tell you where the design has since evolved.  (For the better,
we hope).  In any event, for the latest Perl 6 design (or to figure out
any cryptic remarks below) you should read the Synopses, which are kept
very much more up-to-date than either the Apocalypses or Exegeses.]</p>
<ul>
<p><i>As soon as she walked through my door I knew her type: she was an
argument waiting to happen. I wondered if the argument was required...
or merely optional? Guess I'd know the parameters soon enough.</i></p>
<p><i>&quot;I'm Star At Data&quot;, she offered.</i></p>
<p><i>She made it sound like a pass. But was the pass by name? Or by position?</i></p>
<p><i>&quot;I think someone's trying to execute me. Some caller.&quot;</i></p>
<p><i>&quot;Okay, I'll see what I can find out. Meanwhile, we're
gonna have to limit the scope of your accessibility.&quot;</i></p>
<p><i>&quot;I'd prefer not to be bound like that,&quot; she replied.</i></p>
<p><i>&quot;I see you know my methods,&quot; I shot back.</i></p>
<p><i>She just stared at me, like I was a block.
Suddenly I wasn't surprised someone wanted to dispatch her.</i></p>
<p><i>&quot;I'll return later,&quot; she purred. &quot;Meanwhile, I'm counting on you to give
me some closure&quot;.</i></p>
<p><i>It was gonna be another routine investigation.</i></p>
<ul>
<li><a name='&ndash; Dashiell Hammett, &quot;The Maltese Camel&quot;'></a>&ndash; Dashiell Hammett, &quot;The Maltese Camel&quot;</li>
</ul>
</ul>
<p>This Exegesis explores the new subroutine semantics described in
Apocalypse 6. Those new semantics greatly increase the power and
flexibility of subroutine definitions, providing required and optional
formal parameters, named and positional arguments, a new and extended
operator overloading syntax, a far more sophisticated type system,
multiple dispatch, compile-time macros, currying, and subroutine wrappers.</p>
<p>As if that weren't bounty enough, Apocalypse 6 also covers the
object-oriented subroutines: methods and submethods. We will, however,
defer a discussion of those until Exegesis 12.</p>
<a name='Playing our parts'></a><h1>Playing our parts</h1>
<p>Suppose we want to be able to partition a list into two arrays (hereafter
known as &quot;sheep&quot; and &quot;goats&quot;), according to some user-supplied
criterion. We'll call the necessary subroutine <code>&amp;part</code> &ndash;
because it <i>part</i>itions a list into two <i>part</i>s.</p>
<p>In the most general case, we could specify how <code>&amp;part</code> splits the list
up by passing it a subroutine. <code>&amp;part</code> could then call that subroutine
for each element, placing the element in the &quot;sheep&quot; array if the
subroutine returns true, and into the &quot;goats&quot; array otherwise. It would
then return a list of references to the two resulting arrays.</p>
<p>For example, calling:</p>
<pre>    ($cats, $chattels) = part &amp;is_feline, @animals;</pre>
<p>would result in <code>$cats</code> being assigned a reference to an array
containing all the animals that are feline, and <code>$chattels</code> being
assigned a reference to an array containing everything else that exists
merely for the convenience of cats.</p>
<p>Note that in the above example (and throughout the remainder of this
discussion), when we're talking about a subroutine as an object in its
own right, we'll use the <code>&amp;</code> sigil; but when we're talking about a call
to the subroutine, there will be no <code>&amp;</code> before its name. That's a
distinction Perl 6 enforces too: subroutine calls never have an
ampersand; references to the corresponding <code>Code</code> object always do.</p>
<a name='Part the first'></a><h1>Part the first</h1>
<p>The Perl 6 implementation of <code>&amp;part</code> would therefore be:</p>
<pre>    sub part (Code $is_sheep, *@data) {
        my (@sheep, @goats);
        for @data {
            if $is_sheep($_) { push @sheep, $_ }
            else             { push @goats, $_ }
        }
        return (\@sheep, \@goats);
    }</pre>
<p>As in Perl 5, the <code>sub</code> keyword declares a subroutine. As in Perl 5, the name
of the subroutine follows the <code>sub</code> and &ndash; assuming that name doesn't include
a package qualifier &ndash;  the resulting subroutine is installed into the current
package.</p>
<p><b>Un</b>like Perl 5, in Perl 6 we are allowed to specify a formal parameter list
after the subroutine's name. This list consists of zero or more parameter
variables. Each of these parameter variables is really a lexical variable
declaration, but because they're in a parameter list we don't need to (and
aren't allowed to!) use the keyword <code>my</code>.</p>
<p>Just as with a regular variable, each parameter can be given a storage type,
indicating what kind of value it is allowed to store. In the above example,
for instance, the <code>$is_sheep</code> parameter is given the type <code>Code</code>, indicating
that it is restricted to objects of that type (i.e. the first argument must be
a subroutine or block).</p>
<p>Each of these parameter variables is automatically scoped to the body of the
subroutine, where they can be used to access the arguments with which the
subroutine was called.</p>
<p>A word about terminology: An &quot;argument&quot; is a item in the list of data
that is passed as part of a subroutine call. A &quot;parameter&quot; is a special
variable inside the subroutine itself. So the subroutine call sends arguments,
which the subroutine then accesses via its parameters.</p>
<p>Perl 5 has parameters too, but they're not user-specifiable. They're always
called <code>$_[0]</code>, <code>$_[1]</code>, <code>$_[2]</code>, etc.</p>
<a name='Not-so-secret alias'></a><h2>Not-so-secret alias</h2>
<p>However, one way in which Perl 5 and Perl 6 parameters <i>are</i> similar is that,
unlike Certain Other Languages, Perl parameters don't receive copies of their
respective arguments. Instead, Perl parameters become <i>aliases</i> for the
corresponding arguments.</p>
<p>That's already the case in Perl 5. So, for example, we can write
a temperature conversion utility like:</p>
<pre>    # Perl 5 code...
    sub Fahrenheit_to_Kelvin {
        $_[0] -= 32;
        $_[0] /= 1.8;
        $_[0] += 273.15;
    }

    # and later...

    Fahreheit_to_Kelvin($reactor_temp);</pre>
<p>When the subroutine is called, within the body of
<code>&amp;Fahreheit_to_Kelvin</code> the <code>$_[0]</code> variable becomes just another name
for <code>$reactor_temp</code>. So the changes the subroutine makes to <code>$_[0]</code>
are really being made to <code>$reactor_temp</code>, and at the end of the call
<code>$reactor_temp</code> has been converted to the new temperature scale.</p>
<p>That's very handy when we intend to change the values of arguments (as in the
above example), but it's potentially a very nasty trap too. Many programmers,
accustomed to the pass-by-copy semantics of other languages, will
unconsciously fall into the habit of treating the contents of <code>$_[0]</code>
as if they were a copy. Eventually that will lead to some subroutine
unintentionally changing one of its arguments &ndash; a bug that is often very
hard to diagnose and frequently even harder to track down.</p>
<p>So Perl 6 modifies the way parameters and arguments interact. Explicit
parameters are still aliases to the original arguments, but in Perl 6
they're <b>constant</b> aliases by default. That means, unless we
specifically tell Perl 6 otherwise, it's illegal to change an argument
by modifying the corresponding parameter within a subroutine.</p>
<p>[Update: We now say that they are <code>readonly</code> aliases.  That's because
they aren't necessarily constant from call to call.]</p>
<p>All of which means that a the na&iuml;ve translation of
<code>&amp;Fahreheit_to_Kelvin</code> to Perl 6 isn't going to work:</p>
<pre>    # Perl 6 code...
    sub Fahrenheit_to_Kelvin(Num $temp) {
        $temp -= 32;
        $temp /= 1.8;
        $temp += 273.15;
    }</pre>
<p>That's because <code>$temp</code> (and hence the actual value it's an alias for) is
treated as a constant within the body of <code>&amp;Fahrenheit_to_Kelvin</code>. In
fact, we'd get a compile time error message like:</p>
<pre>    Cannot modify constant parameter ($temp) in &amp;Fahrenheit_to_Kelvin</pre>
<p>If we want to be able to modify arguments via Perl 6 parameters, we have
to say so up front, by declaring them <code>is rw</code> (&quot;read-write&quot;):</p>
<pre>    sub Fahrenheit_to_Kelvin (Num $temp is rw) {
        $temp -= 32;
        $temp /= 1.8;
        $temp += 273.15;
    }</pre>
<p>This requires a few extra keystrokes when the old bahaviour is needed,
but saves a huge amount of hard-to-debug grief in the most common
cases. And, as a bonus, an explicit <code>is rw</code> declaration means that
the compiler can generally catch mistakes like this:</p>
<pre>    $absolute_temp = Fahrenheit_to_Kelvin(212);</pre>
<p>Because we specified that the <code>$temp</code> argument has to be read-writeable,
the compiler can easily catch attempts to pass in a read-only value.</p>
<p>Alternatively, we might prefer that <code>$temp</code> not be an alias at all. We
might prefer that <code>&amp;Fahrenheit_to_Kelvin</code> take a <i>copy</i> of its argument,
which we could then modify without affecting the original, ultimately
returning it as our converted value. We can do that too in Perl 6,
using the <code>is copy</code> trait:</p>
<pre>    sub Fahrenheit_to_Kelvin(Num $temp is copy) {
        $temp -= 32;
        $temp /= 1.8;
        $temp += 273.15;
        return $temp;
    }</pre>
<a name='Defining the parameters'></a><h2>Defining the parameters</h2>
<p>Meanwhile, back at the <code>&amp;part</code>, we have:</p>
<pre>    sub part (Code $is_sheep, *@data) {...}</pre>
<p>which means that <code>&amp;part</code> expects its first argument to be a scalar
value of type <code>Code</code> (or <code>Code</code> reference). Within the subroutine that
first argument will thereafter be accessed via the name <code>$is_sheep</code>.</p>
<p>[Update: These days you'd just declare <code>&amp;is_sheep</code>, which also introduces
the bare name so you can call it without the sigil.]</p>
<p>The second parameter (<code>*@data</code>) is what's known as a &quot;slurpy array&quot;.
That is, it's an array parameter with the special marker (<code>*</code>)
in front of it, indicating to the compiler that <code>@data</code> is supposed to
grab all the remaining arguments passed to <code>&amp;part</code> and make each
element of <code>@data</code> an alias to one of those arguments.</p>
<p>In other words, the <code>*@data</code> parameter does just what <code>@_</code> does in
Perl 5: it grabs all the available arguments and makes its elements
aliases for those arguments. The only differences are that in Perl 6
we're allowed to give that slurpy array a sensible name, and we're
allowed to specify other individual parameters before it &ndash; to give
separate sensible names to one or more of the preliminary arguments
to the call.</p>
<p>But why (you're probably wondering) do we need an asterisk for that? Surely if
we had defined <code>&amp;part</code> like this:</p>
<pre>    sub part (Code $is_sheep, @data) {...}    # note: no asterisk on @data</pre>
<p>the array in the second parameter slot would have slurped up all the remaining
arguments anyway?</p>
<p>Well, no. Declaring a parameter to be a regular (non-slurpy) array tells
the subroutine to expect the corresponding argument to be an actual
array (or an array reference). So if <code>&amp;part</code> had been defined
with its second parameter just <code>@data</code> (rather than <code>*@data</code>), then we could
call it like this:</p>
<pre>    part \&amp;selector, @animal_sounds;</pre>
<p>or this:</p>
<pre>    part \&amp;selector, [&quot;woof&quot;,&quot;meow&quot;,&quot;ook!&quot;];</pre>
<p>but not like this:</p>
<pre>    part \&amp;selector, &quot;woof&quot;, &quot;meow&quot;, &quot;ook!&quot;;</pre>
<p>In each case, the compiler would compare the type of the second argument with
the type required by the second parameter (i.e. an <code>Array</code>). In the first two
cases, the types match and everything is copacetic. But in the third case, the
second argument is a string, not an array or array reference, so we
get a compile-time error message:</p>
<pre>    Type mismatch in call to &amp;part: @data expects Array but got Str instead</pre>
<p>Another way of thinking about the difference between slurpy and regular
parameters is to realize that a slurpy parameter imposes a list (i.e.
flattening) context on the corresponding arguments, whereas a regular,
non-slurpy parameter doesn't flatten or listify. Instead, it insists on
a single argument of the correct type.</p>
<p>So, if we want <code>&amp;part</code> to handle raw lists as data, we need to tell the
<code>@data</code> parameter to take whatever it finds &ndash; array or list &ndash; and
flatten everything down to a list. That's what the asterisk on <code>*@data</code> does.</p>
<p>Because of that all-you-can-eat behaviour, slurpy arrays like this are
generally placed at the very end of the parameter list and
used to collect data for the subroutine. The preceding non-slurpy
arguments generally tell the subroutine <i>what to do</i>; the slurpy array
generally tells it <i>what to do it to</i>.</p>
<a name='Splats and slurps'></a><h2>Splats and slurps</h2>
<p>Another aspect of Perl 6's distinction between slurpy and non-slurpy
parameters can be seen when we write a subroutine that takes multiple
scalar parameters, but then try to pass an array to that subroutine.</p>
<p>For example, suppose we wrote:</p>
<pre>    sub log($message, $date, $time) {...}</pre>
<p>If we happen to have the date and time in a handy array, we might expect that
we could just call <code>log</code> like so:</p>
<pre>    log(&quot;Starting up...&quot;, @date_and_time);</pre>
<p>We might then be surprised when this fails even to compile.</p>
<p>The problem is that each of <code>&amp;log</code>'s three scalar parameters imposes a
scalar context on the corresponding argument in any call to <code>log</code>. So
<code>&quot;Starting up...&quot;</code> is first evaluated in the scalar context imposed by
the <code>$message</code> parameter, and the resulting string is bound to
<code>$message</code>. Then <code>@date_and_time</code> is evaluated in the scalar context
imposed by <code>$date</code>, and the resulting array reference is bound to
<code>$date</code>. Then the compiler discovers that there is no third argument to
bind to the <code>$time</code> parameter, and kills your program.</p>
<p>Of course, it <b>has</b> to work that way, or we don't get the ever-so-useful
&quot;array parameter takes an unflattened array argument&quot; behaviour
described earlier. Unfortunately, that otherwise admirable behaviour is
actually getting in the way here and preventing <code>@date_and_time</code> from
flattening as we want.</p>
<p>So Perl 6 also provides a simple way of explicitly flattening an
array (or a hash for that matter): the unary prefix <code>*</code> operator:</p>
<pre>    log(&quot;Starting up...&quot;, *@date_and_time);</pre>
<p>This operator (known as &quot;splat&quot;) simply flattens its argument into a list.
And since it's a unary operator, it does that flattening <b>before</b>
the arguments are bound to their respective parameters.</p>
<p>The syntactic similarity of a &quot;slurpy&quot; <code>*</code> in a parameter list, and a
&quot;splatty&quot; <code>*</code> in an argument list is quite deliberate. It reflects a
behavioural similarity: just as a slurpy asterisk implicitly flattens any
argument to which its parameter is bound, so too a splatty asterisk explicitly
flattens any argument to which it is applied.</p>
<p>[Update: We had better uses for a &quot;splat&quot; operator, so this flattening is
now performed by the <code>[,]</code> reduce operator, which pretends the values
passed on the right were originally separated by actual commas.  See S03
for more about reduce operators.]</p>
<a name='I do declare'></a><h2>I do declare</h2>
<p>By the way, take another look at those examples above &ndash; the ones with
the <code>{...}</code> where their subroutine bodies should be. Those dots
aren't just metasyntactic; they're real executable Perl 6 code.
A subroutine definition with a <code>{...}</code> for its body isn't actually a
<i>definition</i> at all. It's a <i>declaration</i>.</p>
<p>In the same way that the Perl 5 declaration:</p>
<pre>    # Perl 5 code...
    sub part;</pre>
<p>states that there exists a subroutine <code>&amp;part</code>, without actually saying how
it's implemented, so too:</p>
<pre>    # Perl 6 code...
    sub part (Code $is_sheep, *@data) {...}</pre>
<p>states that there exists a subroutine <code>&amp;part</code> that takes a <code>Code</code> object and
a list of data, without saying how it's implemented.</p>
<p>In fact, the old <code>sub part;</code> syntax is no longer allowed; in Perl 6 you have
to yada-yada-yada when you're making a declaration.</p>
<a name='Body parts'></a><h2>Body parts</h2>
<p>With the parameter list taking care of getting the right arguments into the
right parameters in the right way, the body of the <code>&amp;part</code> subroutine is
then quite straightforward:</p>
<pre>    {
        my (@sheep, @goats);
        for @data {
            if $is_sheep($_) { push @sheep, $_ }
            else             { push @goats, $_ }
        }
        return (\@sheep, \@goats);
    }</pre>
<p>According to the original specification, we need to return references to
two arrays. So we first create those arrays. Then we iterate through
each element of the data (which the <code>for</code> aliases to <code>$_</code>, just as in
Perl 5). For each element, we take the <code>Code</code> object that was passed
as <code>$is_sheep</code> (let's just call it the <i>selector</i> from now on) and we call
it, passing the current data element. If the selector returns true, we
push the data element onto the array of &quot;sheep&quot;, otherwise it is
appended to the list of &quot;goats&quot;. Once all the data has been divvied up,
we return references to the two arrays.</p>
<p>Note that, if this were Perl 5, we'd have to unpack the <code>@_</code> array into
a list of lexical variables and then explicitly check that <code>$is_sheep</code>
is a valid <code>Code</code> object. In the Perl 6 version there's no <code>@_</code>, the
parameters are already lexicals, and the type-checking is handled
automatically.</p>
<a name='Call of the wild'></a><h2>Call of the wild</h2>
<p>With the explicit parameter list in place, we can use <code>&amp;part</code> in a variety of
ways. If we already have a subroutine that is a suitable test:</p>
<pre>    sub is_feline ($animal) {
        return $animal.isa(Cat);
    }</pre>
<p>then we can just pass that to <code>&amp;part</code>, along with the data to be partitioned,
then grab the two array references that come back:</p>
<pre>    ($cats, $chattels) = part &amp;is_feline, @animals;</pre>
<p>This works fine, because the first parameter of <code>&amp;part</code> expects a
<code>Code</code> object, and that's exactly what <code>&amp;is_feline</code> is. Note that we
couldn't just put <code>is_feline</code> there (i.e. without the ampersand),
since that would indicate a <i>call</i> to <code>&amp;is_feline</code>, rather than a
reference to it.</p>
<p>In Perl 5 we'd have had to write <code>\&amp;is_feline</code> to get a reference to the
subroutine. However, since the <code>$is_sheep</code> parameter specifies that the
first argument must be a scalar (i.e. it imposes a scalar context on the
first argument slot), in Perl 6 we don't have to explicit create a
subroutine reference. Putting a code object in the scalar context
automagically en-references it (just as an array or hash is
automatically converted to a reference in scalar context). Of course, an
explicit <code>Code</code> reference is perfectly acceptable there too:</p>
<pre>    ($cats, $chattels) = part \&amp;is_feline, @animals;</pre>
<p>Alternatively, rather than going to the trouble of declaring a separate
subroutine to sort our sheep from our goats, we might prefer to conjure
up a suitable (anonymous) subroutine on the spot:</p>
<pre>    ($cats, $chattels) = part sub ($animal) { $animal.isa(Animal::Cat) }, @animals;</pre>
<a name='In a bind'></a><h2>In a bind</h2>
<p>So far we've always captured the two array references returned from the
<code>part</code> call by assigning the result of the call to a list of scalars.
But we might instead prefer to bind them to actual arrays:</p>
<pre>    (@cats, @chattels) := part sub($animal) { $animal.isa(Animal::Cat) }, @animals;</pre>
<p>Using binding (<code>:=</code>) instead of assignment (<code>=</code>) causes <code>@cats</code> and
<code>@chattels</code> to become aliases for the two anonymous arrays returned by
<code>&amp;part</code>.</p>
<p>In fact, this aliasing of the two return values to <code>@cats</code> and <code>@chattels</code>
uses <i>exactly</i> the same mechanism that is used to alias subroutine
parameters to their corresponding arguments. We could almost think of
the left-hand side of the <code>:=</code> as a parameter list (in this case,
consisting of two non-slurpy array parameters), and the right-hand side
of the <code>:=</code> as being the corresponding argument list. The only
difference is that the variables on the left-hand side of a <code>:=</code> are
not implicitly treated as constant.</p>
<p>One consequence of the similarities between binding and parameter passing
is that we can put a slurpy array on the left of a binding:</p>
<pre>    (@Good, $Bad, *@Ugly) := (@Adams, @Vin, @Chico, @OReilly, @Lee, @Luck, @Britt);</pre>
<p>The first pseudo-parameter (<code>@Good</code>) on the left expects an array, so
it binds to <code>@Adams</code> from the list on the right.</p>
<p>The second pseudo-parameter (<code>$Bad</code>) expects a scalar. That means it
imposes a scalar context on the second element of the right-hand list.
So <code>@Vin</code> evaluates to a reference to the original array and
<code>$Bad</code> becomes an alias for <code>\@Vin</code>.</p>
<p>The final pseudo-parameter (<code>*@Ugly</code>) is slurpy, so it expects the
rest of the left-hand side to be a list it can slurp up. In order to ensure
that, the slurpy asterisk causes the remaining pseudo-arguments on the
right to be flattened into a list, whose elements are then aliased to
successive elements of <code>@Ugly</code>.</p>
<a name='Who shall sit in judgement?'></a><h2>Who shall sit in judgement?</h2>
<p>Conjuring up an anonymous subroutine in each call to <code>part</code> is
intrinsically neither good nor bad. But it sure is ugly:</p>
<pre>    ($cats, $chattels) = part sub($animal) { $animal.isa(Animal::Cat) }, @animals;</pre>
<p>Fortunately there's a cleaner way to specify the selector within the
call to <code>part</code>. We can use a <i>parameterized block</i> instead:</p>
<pre>    ($cats, $chattels) = part -&gt; $animal { $animal.isa(Animal::Cat) } @animals;</pre>
<p>A parameterized block is just a normal brace-delimited block, except
that you're allowed to put a list of parameters out in front of it,
preceded by an arrow (<code>-&gt;</code>). So the parameterized block in the
above example is:</p>
<pre>    -&gt; $animal { $animal.isa(Animal::Cat) }</pre>
<p>In Perl 6, a block is a subspecies of <code>Code</code> object, so it's perfectly
okay to pass a parameterized block as the first argument to <code>&amp;part</code>.
Like a real subroutine, a parameterized block can be subsequently
invoked, and passed an argument list. So the body of the <code>&amp;part</code>
subroutine will continue to work just fine.</p>
<p>It's important to realize that parameterized blocks <i>aren't</i> subroutines
though. They're blocks, and so there are important differences in their
behaviour. The most important difference is that you can't <code>return</code> from a
parameterized block, the way you can from a subroutine. For example, this:</p>
<pre>    part sub($animal) { return $animal.size &lt; $breadbox }, @creatures</pre>
<p>works fine, returning the result of each size comparison every
time the anonymous subroutine is called within <code>&amp;part</code> .</p>
<p>But in this &quot;pointier&quot; version:</p>
<pre>    part -&gt; $animal { return $animal.size &lt; $breadbox } @creatures</pre>
<p>the <code>return</code> isn't inside a nested subroutine; it's inside a block. So the
first time the parameterized block is executed within <code>&amp;part</code> it causes
the subroutine in which the block was defined (i.e. the subroutine
that's <i>calling</i> <code>part</code>) to return!</p>
<p>Oops.</p>
<p>The problem with that second example, of course, is not that we were too
Lazy to write the full anonymous subroutine. The problem is that we
weren't Lazy enough: we forgot to <i>leave out</i> the <code>return</code>.
Just like a Perl 5 <code>do</code> or <code>eval</code> block, a Perl 6
parameterized block evaluates to the value of the last statement
executed within it. So we only needed to say:</p>
<pre>    part -&gt; $animal { $animal.size &lt; $breadbox } @creatures</pre>
<p>Note too that, because the parameterized block is a block, we don't need to
put a comma after it to separate it from the second argument. In fact,
<i>anywhere</i> a block is used as an argument to a subroutine, any comma before
or after the block is optional.</p>
<p>[Update: The comma is now mandatory because a line-ending right curly
assumes a following semicolon.]</p>
<a name='Cowabunga!'></a><h2>Cowabunga!</h2>
<p>Even with the slight abbreviation provided by using a parameterized
block instead of an anonymous subroutine, it's all too easy to lose
track of the the actual data (i.e. <code>@animals</code>) when it's buried at the
end of that long selector definition.</p>
<p>But we can help it stand out a little better by using a new feature of
Perl 6: the &quot;pipeline&quot; operator:</p>
<pre>    ($cats, $chattels) = part sub($animal) { $animal.isa(Animal::Cat) } &lt;== @animals;</pre>
<p>The <code>&lt;==</code> operator takes a subroutine <i>call</i> as its left-hand
argument and a list of data as its right-hand arguments. The subroutine
being called on the left must have a slurpy array parameter (e.g.
<code>*@data</code>) and the list on the operator's right is then bound to that
parameter.</p>
<p>In other words, a <code>&lt;==</code> in a subroutine call marks the end of
the specific arguments and the start of the slurped data.</p>
<p>Pipelines are more interesting when there are several stages to the process,
as in this Perl 6 version of the Schwartzian transform:</p>
<pre>    @shortest_first = map  { .key }                     # 4
                  &lt;== sort { $^a.value &lt;=&gt; $^b.value }  # 3
                  &lt;== map  { $_ =&gt; .height }            # 2
                  &lt;== @animals;                         # 1</pre>
<p>This example takes the array <code>@animals</code>, flattens it into a list (#1),
pipes that list in as the data for a <code>map</code> operation (#2), takes the
resulting list of object/height pairs and pipes that in to
the <code>sort</code> (#3), then takes the resulting sorted list of pairs and
<code>map</code>s out just the sorted objects (#4).</p>
<p>Of course, since the data lists for all of these functions always come
at the end of the call anyway, we could have just written that as:</p>
<pre>    @shortest_first = map  { .key }                     # 4
                      sort { $^a.value &lt;=&gt; $^b.value }  # 3
                      map  { $_ =&gt; .height }            # 2
                      @animals;                         # 1</pre>
<p>[Update: Such blocks now require trailing commas.]</p>
<p>But there's no reason to stint ourselves: the pipelines cost nothing in
performance, and often make the flow of data much clearer.</p>
<p>One problem that many people have with pipelined list processing
techniques like the Schwartzian Transform is that the pipeline flows the
&quot;wrong&quot; way: the code reads left-to-right/top-to-bottom but the data
(and execution) runs right-to-left/bottom-to-top. Happily, Perl 6 has a
solution for that too. It provides a &quot;reversed&quot; version of the pipeline
operator, to make it easy to create left-to-right pipelines:</p>
<pre>    @animals ==&gt; map  { $_ =&gt; .height }              # 1
             ==&gt; sort { $^a.value &lt;=&gt; $^b.value }    # 2
             ==&gt; map  { .key }                       # 3
             ==&gt; @shortest_first;                    # 4</pre>
<p>This version works exactly the same as the previous
right-to-left/bottom-to-top examples, except that now the various components
of the pipeline are written and performed in the &quot;natural&quot; order.</p>
<p>The <code>==&gt;</code> operator is the mirror-image of <code>&lt;==</code>, both visually
and in its behaviour. That is, it takes a subroutine call as its right-hand
argument and a list of data on its left, and binds the left-hand
list to the slurpy array parameter of the subroutine being called on
the right.</p>
<p>Note that this last example makes use of a special dispensation given
to both pipeline operators. The argument on the &quot;sharp&quot; side is supposed
to be a subroutine call. However, if it is a variable, or a list of
variables, then the pipeline operator simply assigns the list from its
&quot;blunt&quot; side to variable (or list) on its &quot;sharp&quot; side.</p>
<p>[Update: Actually, it's bound, not assigned.]</p>
<p>Hence, if we preferred to partition our animals left-to-right, we could
write:</p>
<pre>    @animals ==&gt; part sub ($animal) { $animal.isa(Animal::Cat) } ==&gt; ($cats, $chattels);</pre>
<a name='The incredible shrinking selector'></a><h2>The incredible shrinking selector</h2>
<p>Of course, even with a parameterized block instead of an anonymous subroutine,
the definition of the selector argument is still klunky:</p>
<pre>    ($cats, $chattels) = part -&gt; $animal { $animal.isa(Animal::Cat) } @animals;</pre>
<p>But it doesn't have to be so intrusive. There's another way to create a
parameterized block. Instead of explicitly enumerating the parameters after a
<code>-&gt;</code>, we could use <i>placeholder variables</i>.</p>
<p>As explained in Apocalypse 4, a placeholder variable is one whose sigil
is immediately followed by a caret (<code>^</code>). Any block containing one or
more placeholder variables is automatically a parameterized block,
without the need for an explicit <code>-&gt;</code> or parameter list. Instead,
the block's parameter list is determined automatically from the set of
placeholder variables enclosed by the block's braces.</p>
<p>So we could simplify our partitioning to:</p>
<pre>    ($cats, $chattels) = part { $^animal.isa(Animal::Cat) } @animals;</pre>
<p>Here <code>$^animal</code> is a placeholder, so the block immediately surrounding it
becomes a parameterized block &ndash; in this case with exactly one parameter.</p>
<p>Better still, any block containing a <code>$_</code> is also a parameterized block
&ndash; with a single parameter named <code>$_</code>. So we could dispense with the explicit
placeholder and just write our partitioning statement:</p>
<pre>    ($cats, $chattels) = part { $_.isa(Animal::Cat) } @animals;</pre>
<p>which is really a shorthand for the parameterized block:</p>
<pre>    ($cats, $chattels) = part -&gt; $_ { $_.isa(Animal::Cat) } @animals;</pre>
<p>And come to think of it, since we now have the unary dot operator (which
calls a method using <code>$_</code> as the invocant), we don't even need
the explicit <code>$_</code>:</p>
<pre>    ($cats, $chattels) = part { .isa(Animal::Cat) } @animals;</pre>
<a name='Part the second'></a><h1>Part the second</h1>
<p>But wait, there's even...err...less!</p>
<p>We could very easily extend <code>&amp;part</code> so that we don't even need the block in
that case; so that we could just pass the raw class in as the first parameter:</p>
<pre>    ($cats, $chattels) = part Animal::Cat, @animals;</pre>
<p>To do that, the type of the first parameter will have to become <code>Class</code>,
which is the (meta-)type of all classes. However, if we changed <code>&amp;part</code>'s
parameter list in that way:</p>
<pre>    sub part (Class $is_sheep, *@data) {...}</pre>
<p>then all our existing code that currently passes <code>Code</code> objects as
<code>&amp;part</code>'s first argument will break.</p>
<p>[Update: Except there's no such thing as a <code>Class</code> type in Perl 5.  See S12.]</p>
<p>Somehow we need to be able to pass <i>either</i> a <code>Code</code> object <i>or</i> a <code>Class</code>
as <code>&amp;part</code>'s first argument. And to accomplish that we need to take a short
detour into...</p>
<a name='The Wonderful World of Junctions'></a><h2>The Wonderful World of Junctions</h2>
<p>Perl 6 introduces an entirely new scalar data-type: the &quot;junction&quot;.
A junction is a single scalar value that can act like two or more values at
once. So, for example, we can create a value that behaves like any of
the values <code>1</code>, <code>4</code>, or <code>9</code>, by writing:</p>
<pre>    $monolith = any(1,4,9);</pre>
<p>The scalar value returned by <code>any</code> and subsequently stored in
<code>$monolith</code> is equal to <code>1</code>. And at the same time it's also equal to
<code>4</code>. And to <code>9</code>. It's equal to any of them. Hence the name of the <code>any</code>
function that we used to set it up.</p>
<p>What good it that? Well, if it's equal to &quot;any of them&quot; then, with a single
comparison, we can test if some other value is also equal to &quot;any of them&quot;:</p>
<pre>    if $dave == any(1,4,9) {
        print &quot;I'm sorry, Dave, you're just a square.&quot;
    } </pre>
<p>That's considerably shorter (and more maintainable) than:</p>
<pre>    if $dave == 1 || $dave == 4 || $dave == 9 { 
        print &quot;I'm sorry, Dave, you're just a square.&quot;
    } </pre>
<p>It even reads more naturally.</p>
<p>Better still, Perl 6 provides an n-ary operator that builds the same kinds of
junctions from its operands:</p>
<pre>    if $dave == 1|4|9 {
        print &quot;I'm sorry, Dave, you're just a square.&quot;
    } </pre>
<p>Once you get used to this notation, it too is very easy to follow:
<i>if Dave equals 1 or 4 or 9...</i>.</p>
<p>(And, yes, the Perl 5 bitwise OR is still available in Perl 6;
it's just spelled differently now).</p>
<p>The <code>any</code> function is more useful when the values under consideration
are stored in a single array. For example, we could check whether a new
value is bigger than any we've already seen:</p>
<pre>    if $newval &gt; any(@oldvals) {
        print &quot;$newval isn't the smallest.&quot;
    }</pre>
<p>In Perl 5 we'd have to write that:</p>
<pre>    if (grep { $newval &gt; $_ } @oldvals) {
        print &quot;$newval isn't the smallest.&quot;
    }</pre>
<p>which isn't as clear and isn't as quick (since the <code>any</code> version will
short-circuit as soon as it knows the comparison is true, whereas the <code>grep</code>
version will churn through every element of <code>@oldvals</code> no matter what).</p>
<p>An <code>any</code> is even more useful when we have a collection of new values to
check against the old ones. We can say:</p>
<pre>    if any(@newvals) &gt; any(@oldvals) {
        print &quot;Already seen at least one smaller value.&quot;
    }</pre>
<p>instead of resorting to the horror of nested <code>grep</code>s:</p>
<pre>    if (grep { my $old = $_; grep { $_ &gt; $old } @newvals } @oldvals) {
        print &quot;Already seen at least one smaller value.&quot;
    }</pre>
<p>But what if we wanted to check whether <i>all</i> of the new values were
greater than any of the old ones. For that we use a different kind of
junction &ndash; one that is equal to all our values at once (rather than
just any one of them). We can create such a junction with the
<code>all</code> function:</p>
<pre>    if all(@newvals) &gt; any(@oldvals) {
        print &quot;These are all bigger than something already seen.&quot;
    }</pre>
<p>We could also test if all the new values are greater than <i>all</i> the old ones
(not merely greater than at least one of them), with:</p>
<pre>    if all(@newvals) &gt; all(@oldvals) {
        print &quot;These are all bigger than everything already seen.&quot;
    }</pre>
<p>There's an operator for building <code>all</code> junctions too. No prizes for
guessing. It's n-ary <code>&amp;</code>. So, if we needed to check that the maximal
dimension of some object is within acceptable limits, we could say:</p>
<pre>    if $max_dimension &lt; $height &amp; $width &amp; $depth {
        print &quot;A maximal dimension of $max_dimension is okay.&quot;
    }</pre>
<p>That last example is the same as:</p>
<pre>    if $max_dimension &lt; $height
    &amp;&amp; $max_dimension &lt; $width
    &amp;&amp; $max_dimension &lt; $depth {
        print &quot;A maximal dimension of $max_dimension is okay.&quot;
    }</pre>
<p><code>any</code> junctions are known as <i>disjunctions</i>, because they act like
they're in a boolean OR: &quot;this OR that OR the other&quot;. <code>all</code> junctions
are known as <i>conjunctions</i>, because they have an implicit AND between
their values &ndash; &quot;this AND that AND the other&quot;.</p>
<p>There are two other types of junction available in Perl 6:
<i>abjunctions</i> and <i>injunctions</i>. An abjunction is created
using the <code>one</code> function and represents exactly one of its possible
values at any given time:</p>
<pre>    if one(@roots) == 0 {
        print &quot;Unique root to polynomial.&quot;;
    }</pre>
<p>In other words, it's as though there was an implicit n-ary XOR between each
pair of values.</p>
<p>Injunctions represent none of their values and hence are constructed with a
built-in named <code>none</code>:</p>
<pre>    if $passwd eq none(@previous_passwds) {
        print &quot;New password is acceptable.&quot;;
    }</pre>
<p>They're like a multi-part NEITHER...NOR...NOR...</p>
<p>We can build a junction out of any scalar type. For example, strings:</p>
<pre>    my $known_title = 'Mr' | 'Mrs' | 'Ms' | 'Dr' | 'Rev';

    if %person{title} ne $known_title {
        print &quot;Unknown title: %person{title}.&quot;;
    }</pre>
<p>or even <code>Code</code> references:</p>
<pre>    my &amp;ideal := \&amp;tall &amp; \&amp;dark &amp; \&amp;handsome;

    if ideal($date) {   # Same as: if tall($date) &amp;&amp; dark($date) &amp;&amp; handsome($date)
        swoon();
    }</pre>
<a name='The best of both worlds'></a><h2>The best of both worlds</h2>
<p>So a disjunction (<code>any</code>) allows us to create a scalar value that is
<i>either</i> this <i>or</i> that.</p>
<p>But, in Perl 6, classes (or, more specifically, <code>Class</code> objects) are
scalar values. So it follows that we can create a disjunction of
classes. For example:</p>
<pre>    Floor::Wax | Dessert::Topping</pre>
<p>That gives us a type that can be <i>either</i> <code>Floor::Wax</code> <i>or</i>
<code>Dessert::Topping</code>. So a variable declared with that type:</p>
<pre>    my Floor::Wax|Dessert::Topping $shimmer;</pre>
<p>can store <i>either</i> a <code>Floor::Wax</code> object <i>or</i> a <code>Dessert::Topping</code> object. And a parameter declared with that type:</p>
<pre>    sub advertise(Floor::Wax|Dessert::Topping $shimmer) {...}</pre>
<p>can be passed an argument that is of either type.</p>
<a name='Matcher smarter, not harder'></a><h2>Matcher smarter, not harder</h2>
<p>So, in order to extend <code>&amp;part</code> to accept a <code>Class</code> as its
first argument, whilst still allowing it to accept a <code>Code</code> object in that
position, we just use a type junction:</p>
<pre>    sub part (Code|Class $is_sheep, *@data) {
        my (@sheep, @goats);
        for @data {
            when $is_sheep { push @sheep, $_ }
            default        { push @goats, $_ }
        }
        return (\@sheep, \@goats);
    }</pre>
<p>There are only two differences between this version and the
<i><a href='#Part the first'>previous one</a></i>. The first difference is, of course,
that we have changed the type of the first parameter. Previously it was
<code>Code</code>; now it's <code>Code|Class</code>.</p>
<p>[Update: Nowadays it's just role <code>Selector</code> (which does
smart matchability), possibly synonymous with <code>Any</code>.]</p>
<p>The second change is in the body of the subroutine itself. We replaced
the partitioning <code>if</code> statement:</p>
<pre>    for @data {
        if $is_sheep($_) { push @sheep, $_ }
        else             { push @goats, $_ }
    }</pre>
<p>with a switch:</p>
<pre>    for @data {
        when $is_sheep { push @sheep, $_ }
        default        { push @goats, $_ }
    }</pre>
<p>Now the actual work of categorizing each element as a &quot;sheep&quot; or a
&quot;goat&quot; is done by the <code>when</code> statement, because:</p>
<pre>    when $is_sheep { push @sheep, $_ }</pre>
<p>is equivalent to:</p>
<pre>    if $_ ~~ $is_sheep { push @sheep, $_; next }</pre>
<p>When <code>$is_sheep</code> is a subroutine reference, that implicit smart-match
will simply pass <code>$_</code> (i.e. the current data element) to the subroutine
and then evaluate the return value as a boolean. On the other hand, when
<code>$is_sheep</code> is a class, the smart-match will check to see if the
object in <code>$_</code> belongs to the same class (or to some derived class).</p>
<p>So the single <code>when</code> statement handles either type of selector
&ndash; <code>Code</code> or <code>Class</code> &ndash; automagically. That's why it's known as
smart-matching.</p>
<p>Having now allowed class names as selectors, we can take the final step and
simplify:</p>
<pre>    ($cats, $chattels) = part { .isa(Animal::Cat) } @animals;</pre>
<p>to:</p>
<pre>    ($cats, $chattels) = part Animal::Cat, @animals;</pre>
<p>Note, however, that the comma is back. Only blocks can appear in argument
lists without accompanying commas, and the raw class isn't a block.</p>
<p>[Update: Smart matching uses <code>.does</code>, not <code>.isa</code> these days.]</p>
<a name='Partitioning rules!'></a><h1>Partitioning rules!</h1>
<p>Now that the <code>when</code>'s implicit smart-match is doing the hard work of deciding
how to evaluate each data element against the selector, adding new kinds of
selectors becomes trivial.</p>
<p>For example, here's a third version of <code>&amp;part</code> which also allows Perl 6
rules (i.e. patterns) to be used to partition a list:</p>
<pre>    sub part (Code|Class|Rule $is_sheep, *@data) {
        my (@sheep, @goats);
        for @data {
            when $is_sheep { push @sheep, $_ }
            default        { push @goats, $_ }
        }
        return (\@sheep, \@goats);</pre>
<p>All we needed to do was to tell <code>&amp;part</code> that its first argument was also
allowed to be of type <code>Rule</code>. That allows us to call <code>&amp;part</code> like this:</p>
<pre>    ($cats, $chattels) = part /meow/, @animal_sounds;</pre>
<p>In the scalar context imposed by the <code>$is_sheep</code> parameter, the
<code>/meow/</code> pattern evaluates to a <code>Rule</code> object (rather than immediately
doing a match). That <code>Rule</code> object is then bound to <code>$is_sheep</code> and
subsequently used as the selector in the <code>when</code> statement.</p>
<p>[Update: These are now called <code>Regex</code> objects.]</p>
<p>Note that the body of this third version is exactly the same as that of
the previous version. No change is required because, when it
detects that <code>$is_sheep</code> is a <code>Rule</code> object, the <code>when</code>'s smart-matching
will automagically do a pattern match.</p>
<p>In the same way, we could further extend <code>&amp;part</code> to allow the user to pass a
hash as the selector:</p>
<pre>    my %is_cat = (
        cat =&gt; 1, tiger =&gt; 1, lion =&gt; 1, leopard =&gt; 1, # etc.
    );

    ($cats, $chattels) = part %is_cat, @animal_names;</pre>
<p>simply by changing the parameter list of <code>&amp;part</code> to:</p>
<pre>    sub part (Code|Class|Rule|Hash $is_sheep, *@data) {
        # body exactly as before
    }</pre>
<p>Once again, the smart-match hidden in the <code>when</code> statement just Does
The Right Thing. On detecting a hash being matched against each datum,
it will use the datum as a key, do a hash look-up, and evaluate the
truth of the corrresponding entry in the hash.</p>
<p>Of course, the ever-increasing disjunction of allowable selector types is
rapidly threatening to overwhelm the entire parameter list. At this point it
would make sense to factor the type-junction out, give it a logical
name, and use that name instead. To do that, we just write:</p>
<pre>    type Selector ::= Code | Class | Rule | Hash;</pre>
<p>[Update: Now written:</p>
<pre>    my subset Selector where Code | Class | Rule | Hash;
    my subset Selector of Any where Code | Class | Rule | Hash;
    my Any subset Selector of Any where Code | Class | Rule | Hash;</pre>
<p>Except that Selector is built in and is more general than that.]</p>
<pre>    sub part (Selector $is_sheep, *@data) {
        # body exactly as before
    }</pre>
<p>The <code>::=</code> binding operator is just like the <code>:=</code> binding operator,
except that it operates at compile-time. It's the right choice here
because types need to be fully defined at compile-time, so the compiler
can do as much static type checking as possible.</p>
<p>The effect of the binding is to make the name <code>Selector</code> an alias for
<code>Code</code> <code>|</code> <code>Class</code> <code>|</code> <code>Rule</code> <code>|</code> <code>Hash</code>. Then we can just use <code>Selector</code> wherever we
want that particular disjunctive type.</p>
<a name='Out with the new and in with the old'></a><h1>Out with the new and in with the old</h1>
<p>Let's take a step back for a moment.</p>
<p>We've already seen how powerful and clean these new-fangled explicit
parameters can be, but maybe you still prefer the Perl 5 approach. After
all, <code>@_</code> was good enough fer Grandpappy when he larned hisself Perl as
a boy, dagnabit!</p>
<p>[Update: As of May 2006, Larry is a Grandpappy too.]</p>
<p>So in Perl 6 we can still pass your arguments the old-fashioned way
and then process them manually:</p>
<pre>    # Still valid Perl 6...
    sub part {
        # Unpack and verify args...
        my ($is_sheep, @data) = @_;
        croak &quot;First argument to &amp;part is not Code, Hash, Rule, or Class&quot;
            unless $is_sheep.isa(Selector);

        # Then proceed as before...
        my (@sheep, @goats);
        for @data {
            when $is_sheep { push @sheep, $_ }
            default        { push @goats, $_ }
        }
        return (\@sheep, \@goats);
    }</pre>
<p>If we declare a subroutine without a parameter list, Perl 6 automatically
supplies one for us. And the one it supplies consists of a single slurpy
array named <code>@_</code>:</p>
<pre>    sub part {...}      # means: sub part (*@_) {...}</pre>
<p>That is, any un-parametered Perl 6 subroutine expects to flatten and then
slurp up an arbitrarily long list of arguments, binding them to the
elements of a parameter called <code>@_</code>. Which is pretty much what a Perl 5
subroutine does. The only important difference is that in Perl 6 that
slurpy <code>@_</code> is, like all Perl 6 parameters, constant by default. So, if
we want the <i>exact</i> behaviour of a Perl 5 subroutine &ndash; including being
able to modify elements of <code>@_</code> &ndash; we need to be explicit:</p>
<pre>    sub part (*@_ is rw) {...}</pre>
<p>Note that &quot;declare a subroutine without a parameter list&quot; <i>doesn't</i>
mean &quot;declare a subroutine with an empty parameter list&quot;:</p>
<pre>    sub part    {...}   # without parameter list
    sub part () {...}   # empty parameter list</pre>
<p>An empty parameter list specifies that the subroutine takes exactly zero
arguments. Whereas a missing paramter list means it takes any number of
arguments and binds them to the implicit parameter <code>@_</code>.</p>
<p>Of course, by using the implicit <code>@_</code> instead of named parameters,
we're merely doing extra work that Perl 6 could do for us, as well as
making the subroutine body more complex, harder to maintain, and slower.
We're also eliminating any chance of Perl 6 identifying argument
mismatches at compile-time. And, unless we're prepared to complexify
the code even further, we're preventing client code from using named
arguments (see <i><a href='#Name your poison'>&quot;Name your poison&quot;</a></i> below).</p>
<p>But this is Perl, not Fascism. We're not in the business of imposing the
One True Coding Style on Perl hackers. So if you want to pass your
arguments the old-fashioned way, Perl 6 makes sure you still can.</p>
<a name='A pair of lists in a list of pairs'></a><h1>A pair of lists in a list of pairs</h1>
<p>Suppose now that, instead of getting a list of array references back, we
wanted to get back a list of <code>key=&gt;value</code> pairs, where each value was one
of the array refs and each key some kind of identifying label (we'll see
why that might be particularly handy <i><a href='#Pair Bonding'>soon</a></i>).</p>
<p>The easiest solution is to use two fixed keys (for example, <code>&quot;sheep&quot;</code>
and <code>&quot;goats&quot;</code>):</p>
<pre>    sub part (Selector $is_sheep, *@data) returns List of Pair {
        my %herd;
        for @data {
            when $is_sheep { push %herd{&quot;sheep&quot;}, $_ }
            default        { push %herd{&quot;goats&quot;}, $_ }
        }
        return *%herd;
    }</pre>
<p>The parameter list of the subroutine is unchanged, but now we've added a
return type after it, using the <code>returns</code> keyword. That return type is <code>List
of Pair</code>, which tells the compiler that any <code>return</code> statements in the
subroutine are expected to return a list of values, each of which is a Perl 6
<code>key=&gt;value</code> pair.</p>
<a name='Parametric types'></a><h2>Parametric types</h2>
<p>Note that this type is different from those we've seen so far: it's
compound. The <code>of Pair</code> suffix is actually an argument that
modifies the principal type <code>List</code>, telling
the container type what kind of value it's allowed to store. This is
possible because <code>List</code> is a <i>parametric type</i>. That is,
it's a type that can be specified with arguments that modify how it
works. The idea is a little like C++ templates, except not quite so
brain-meltingly complicated.</p>
<p>The specific parameters for a parametric type are normally specified in
square brackets, immediately after the class name. And the arguments that
define a particular instance of the class are likewise passed in square
brackets. For example:</p>
<pre>        class Table[Class $of] {...}
        class Logfile[Str $filename] {...}
        module SecureOps[AuthKey $key] {...} 
                
        # and later:

        sub typeset(Table of Contents $toc) {...}
        # Expects an object whose class is Table
        # and which stores Contents objects

        my Logfile[&quot;./log&quot;] $file;
        # $file can only store logfiles that log to ./log

        $plaintext = SecureOps[$KEY]::decode($cryptotext);
        # Only use &amp;decode if our $KEY entitles us to</pre>
<p>Note that type names like <code>Table of Contents</code> and <code>List of Pair</code>
are really just tidier ways to say <code>Table[of=&gt;Contents]</code> and
<code>List[of=&gt;Pair]</code>.</p>
<p>By convention, when we pass an argument to the <code>$of</code> parameter of a
parametric type, we're telling that type that what kind of value we're
expecting it to store. For example: whenever we access an element of
<code>List of Pair</code>, we expect to get back a <code>Pair</code>. Similarly we could
specify <code>List of Int</code>, <code>Array of Str</code>, or <code>Hash of Num</code>.</p>
<p>Admittedly <code>List of Pair</code> doesn't seem <i>much</i> tidier than
<code>List(of=&gt;Pair)</code>, but as container types get more complex, the
advantages start to become obvious. For example, consider a data
structure consisting of an array of arrays of arrays of hashes of
numbers (such as one might use to store, say, several years worth of
daily climatic data). Using the <code>of</code> notation that's just:</p>
<pre>    type Climate::Record ::= Array of Array of Array of Hash of Num;</pre>
<p>Without the <code>of</code> keyword, it's:</p>
<pre>    type Climate::Record ::= Array(of=&gt;Array(of=&gt;Array(of=&gt;Hash(of=&gt;Num))));</pre>
<p>which is starting to look uncomfortably like Lisp.</p>
<p>Note that parametric types may have any number of parameters with any
names we like. But only type parameters named <code>$of</code> have special syntactic
support built into Perl.</p>
<a name='TMTOWTDeclareI'></a><h2>TMTOWTDeclareI</h2>
<p>While we're talking about type declarations, it's worth noting that we
could also have put <code>&amp;part</code>'s new return type out in front (just as
we've been doing with variable and parameter types). However, this is
only allowed for subroutines when the subroutine is explicitly scoped:</p>
<pre>    # lexical subroutine
    my List of Pair sub part (Selector $is_sheep, *@data) {...}</pre>
<p>or:</p>
<pre>    # package subroutine
    our List of Pair sub part (Selector $is_sheep, *@data) {...}</pre>
<p>The return type goes between the scoping keyword (<code>my</code> or <code>our</code>) and the
<code>sub</code> keyword. And, of course, the <code>returns</code> keyword is not used.</p>
<p>Contrariwise, we can also put variable/parameter type information
<i>after</i> the variable name. To do that, we use the <code>of</code> keyword:</p>
<pre>    my sub part ($is_sheep of Selector, *@data) returns List of Pair {...}</pre>
<p>This makes sense, when you think about it. As we saw above, <code>of</code> tells
the preceding container what type of value it's supposed to store, so
<code>$is_sheep of Selector</code> tells <code>$is_sheep</code> it's supposed to store a
<code>Selector</code>.</p>
<p>[Update: The <code>returns</code> type is only the inner type now.  The externally
visible &quot;of&quot; type of a subroutine is declared out front or within
the signature using <code>--&gt;</code> notation.  (Or via an explicit <code>of</code>
trait.)]</p>
<a name='You are what you eat. Not!'></a><h2>You are what you eat. Not!</h2>
<p>Careful though: we have to remember to use <code>of</code> there, not <code>is</code>.
It would be a mistake to write:</p>
<pre>    my sub part ($is_sheep is Selector, *@data) returns List of Pair {...}</pre>
<p>That's because Perl 6 variables and parameters can be more precisely
typed than variables in most other languages. Specifically, Perl 6 allows us
to specify both the <i>storage type</i> of a variable (i.e. what kinds of
values it can contain) and the <i>implementation class</i> of the variable
(i.e. how the variable itself is actually implemented).</p>
<p>The <code>is</code> keyword indicates what a particular container (variable, parameter,
etc.) <i>is</i>. Namely, how it's implemented and how it operates.
So saying:</p>
<pre>    sub bark(@dogs is Pack) {...}</pre>
<p>specifies that, although the <code>@dogs</code> parameter looks like an <code>Array</code>, it's
actually implemented by the <code>Pack</code> class instead.</p>
<p>That declaration is <b>not</b> specifying that the <code>@dogs</code> variable
<i>stores</i> <code>Pack</code> objects. In fact, it's not saying anything at all about
what <code>@dogs</code> stores. So, since its storage type has been left
unspecified, <code>@dogs</code> inherits the default storage type &ndash; <code>Any</code> &ndash;
which allows its elements to store any kind of scalar value.</p>
<p>If we'd wanted to specify that <code>@dogs</code> was a normal array, but that it
can only store <code>Dog</code> objects, we'd need to write:</p>
<pre>    sub bark(@dogs of Dog) {...}</pre>
<p>And if we'd wanted it to store <code>Dog</code>s but be implemented by the
<code>Pack</code> class, we'd have to write:</p>
<pre>    sub bark(@dogs is Pack of Dog) {...}</pre>
<p>Appending <code>is SomeType</code> to a variable or parameter is the Perl 6 equivalent
of Perl 5's <code>tie</code> mechanism, except that the tying is part of the
declaration. For example:</p>
<pre>    my $Elvis is King of Rock&amp;Roll;</pre>
<p>rather than a run-time function call like:</p>
<pre>    # Perl 5 code...
    my $Elvis;
    tie $Elvis, 'King', stores=&gt;all('Rock','Roll');</pre>
<p>In any case, the simple rule for <code>of</code> vs <code>is</code> is: to say what a
variable stores, use <code>of</code>; to say how the variable itself works,
use <code>is</code>.</p>
<a name='Many happy returns'></a><h2>Many happy returns</h2>
<p>Meanwhile, we're still attempting to create a version of <code>&amp;part</code> that
returns a list of pairs. The easiest way to create and return a suitable
list of pairs is to flatten a hash in a list context. Which is precisely
what the <code>return</code> statement does:</p>
<pre>    return *%herd;</pre>
<p>using the splatty star. Although, in this case, we could have simply written:</p>
<pre>    return %herd;</pre>
<p>since the declared return type (<code>List of Pair</code>) automatically imposes list
context (and hence list flattening) on any <code>return</code> statement within <code>&amp;part</code>.</p>
<p>Of course, it will only make sense to return a flattened hash if
we've already partitioned the original data into that hash. So the
bodies of the <code>when</code> and <code>default</code> statements inside <code>&amp;part</code> have to
be changed accordingly. Now, instead of pushing each element onto one of
two separate arrays, we push each element onto one of the two arrays
stored inside <code>%herd</code>:</p>
<pre>    for @data {
        when $is_sheep { push %herd{&quot;sheep&quot;}, $_ }
        default        { push %herd{&quot;goats&quot;}, $_ }
    }</pre>
<a name='It lives!!!!!'></a><h2>It lives!!!!!</h2>
<p>Assuming that each of the hash entries (<code>%herd{&quot;sheep&quot;}</code> and
<code>%herd{&quot;goats&quot;}</code>) will be storing a reference to one of the two arrays,
we can simply push each data element onto the appropriate array.</p>
<p>In Perl 5 we'd have to dereference each of the array references inside our
hash before we could push a new element onto it:</p>
<pre>    # Perl 5 code...
    push @{$herd{&quot;sheep&quot;}}, $_;</pre>
<p>But in Perl 6, the first parameter of <code>push</code> expects an array, so if we
give it an array reference, the interpreter can work out that it
needs to automatically dereference that first argument. So we can just write:</p>
<pre>    # Perl 6 code...
    push %herd{&quot;sheep&quot;}, $_;</pre>
<p>(Remember that, in Perl 6, hashes keep their <code>%</code> sigil, even when being
indexed).</p>
<p>[Update: Now you'd usually write <code>%herd&lt;sheep&gt;</code> most of the time.]</p>
<p>Initially, of course, the entries of <code>%herd</code> don't contain references to
arrays at all; like all uninitialized hash entries, they contain <code>undef</code>.
But, because <code>push</code> itself is defined like so:</p>
<pre>    sub push (@array is rw, *@data) {...}</pre>
<p>an actual read-writable array is expected as the first argument. If a scalar
variable containing <code>undef</code> is passed to such a parameter, Perl 6
detects the fact and autovivifies the necessary array, placing a
reference to it into the previously undefined scalar argument.
That behaviour makes it trivially easy to create subroutines that
autovivify read/write arguments, in the same way that Perl 5's <code>open</code> does.</p>
<p>It's also possible to declare a read/write parameter that <i>doesn't</i>
autovivify in this way: using the <code>is ref</code> trait instead of <code>is rw</code>:</p>
<pre>    sub push_only_if_real_array (@array is ref, *@data) {...}</pre>
<p><code>is ref</code> still allows the parameter to be read from and written to, but
throws an exception if the corresponding argument isn't already a real
referent of some kind.</p>
<a name='A label by any other name'></a><h1>A label by any other name</h1>
<p>Mandating fixed labels for the two arrays being returned seems a little
inflexible, so we could add another &ndash; optional &ndash; parameter via which
user-selected key names could be passed...</p>
<pre>    sub part (Selector $is_sheep,
              Str ?@labels is dim(2) = &lt;&lt;sheep goats&gt;&gt;,</pre>
<p>[Update: Optional parameters are now suffixed with <code>?</code>, but it's
optional if there's a default.  The dimension syntax is different now,
and single angles are used now for <code>qw//</code>.  So we get:</p>
<pre>              Str @labels[^2] = &lt;sheep goats&gt;,</pre>
<p>]</p>
<pre>              *@data
             ) returns List of Pair
    {
        my ($sheep, $goats) is constant = @labels;</pre>
<p>[Update: <code>is readonly</code> now.]</p>
<pre>        my %herd = ($sheep=&gt;[], $goats=&gt;[]);
        for @data {
            when $is_sheep { push %herd{$sheep}, $_ }
            default        { push %herd{$goats}, $_ }
        }
        return *%herd;
    }</pre>
<p>Optional parameters in Perl 6 are prefixed with a <code>?</code> marker (just as
slurpy parameters are prefixed with <code>*</code>). Like required parameters,
optional parameters are passed positionally, so the above example means
that the second argument is expected to be an array of strings. This has
important consequences for backwards compatibility &ndash; as we'll see
<i><a href='#Pipeline to the rescue!'>shortly</a></i>.</p>
<p>As well as declaring it to be optional (using a leading <code>?</code>), we also declare
the <code>@labels</code> parameter to have exactly two elements, by specifying the <code>is
dim(2)</code> trait. The <code>is dim</code> trait takes one or more integer values. The
number of values it's given specifies the number of dimensions the array has;
the values themselves specify how many elements long the array is in each
dimension. For example, to create a four-dimensional array of 7x24x60x60
elements, we'd declare it:</p>
<pre>    my @seconds is dim(7,24,60,60);</pre>
<p>[Update: <code>my @seconds[^7,^24,^60,^60]</code> now.]</p>
<p>In the latest version of <code>&amp;part</code>, the <code>@labels is dim(2)</code> declaration
means that <code>@labels</code> is a normal one-dimensional array, but that it
has only two elements in that one dimension.</p>
<p>The final component of the declaration of <code>@labels</code> is the specification of
its default value. Any optional parameter may be given a default value, to
which it will be bound if no corresponding argument is provided. The default
value can be any expression that yields a value compatible with the
type of the optional parameter.</p>
<p>In the above version of <code>&amp;part</code>, for the sake of backwards
compatibility we make the optional <code>@labels</code> default to the list of two
strings <code>&lt;&lt;sheep goats&gt;&gt;</code>  (using the new Perl 6 list-of-strings
syntax).</p>
<p>Thus if we provide an array of two strings explicitly, the two strings
we provide will be used as keys for the two pairs returned. If we don't
specify the labels ourselves, <code>&quot;sheep&quot;</code> and <code>&quot;goats&quot;</code> will be used.</p>
<a name='Name your poison'></a><h2>Name your poison</h2>
<p>With the latest version of <code>&amp;part</code> defined to return named pairs, we
can now write:</p>
<pre>    @parts = part Animal::Cat, &lt;&lt;cat chattel&gt;&gt;, @animals;
    #    returns: (cat=&gt;[...], chattel=&gt;[...])
    # instead of: (sheep=&gt;[...], goats=&gt;[...])</pre>
<p>The first argument (<code>Animal::Cat</code>) is bound to <code>&amp;part</code>'s <code>$is_sheep</code>
parameter (as before). The second argument (<code>&lt;&lt;cat chattel&gt;&gt;</code>) is
now bound to the optional <code>@labels</code> parameter, leaving the <code>@animals</code>
argument to be flattened into a list and slurped up by the <code>@data</code>
parameter.</p>
<p>We could also pass some, or all, of the arguments as <i>named arguments</i>.
A named argument is simply a Perl 6 pair, where the key is the name of
the intended parameter, and the value is the actual argument to be bound
to that parameter. That makes sense: every parameter we ever declare has to
have a name, so there's no good reason why we shouldn't be allowed to pass it
an argument using that name to single it out.</p>
<p>An important restriction on named arguments is that they cannot come
before positional arguments, or after any arguments that are bound to a
slurpy array. Otherwise, there would be no efficient, single-pass way of
working out which unnamed arguments belong to which parameters.
But apart from that one overarching restriction (which Larry likes
to think of as a zoning law), we're free to pass named arguments in any
order we like. That's a huge advantage in any subroutine that takes a large
number of parameters, because it means we no longer have to remember their
order, just their names.</p>
<p>For example, using named arguments we could rewrite the above <code>part</code> call
as any of the following:</p>
<pre>    # Use named argument to pass optional @labels argument...
    @parts = part Animal::Cat, labels =&gt; &lt;&lt;cat chattel&gt;&gt;, @animals;

    # Use named argument to pass both @labels and @data arguments...
    @parts = part Animal::Cat, labels =&gt; &lt;&lt;cat chattel&gt;&gt;, data =&gt; @animals;

    # The order in which named arguments are passed doesn't matter...
    @parts = part Animal::Cat, data =&gt; @animals, labels =&gt; &lt;&lt;cat chattel&gt;&gt;;

    # Can pass *all* arguments by name...
    @parts = part is_sheep =&gt; Animal::Cat,
                    labels =&gt; &lt;&lt;cat chattel&gt;&gt;,
                      data =&gt; @animals;

    # And the order still doesn't matter...
    @parts = part data =&gt; @animals,
                  labels =&gt; &lt;&lt;cat chattel&gt;&gt;,
                  is_sheep =&gt; Animal::Cat;

    # etc.</pre>
<p>So long as we never put a named argument before a positional argument,
or after any unnamed data for the slurpy array, the named arguments can
appear in any convenient order. They can even be pulled out of a
flattened hash:</p>
<pre>    @parts = part *%args;</pre>
<p>[Update: Now <code>[,]%args</code>.  But we have relaxed the zoning laws into
zoning suggestions.]</p>
<a name='Who gets the last piece of cake?'></a><h2>Who gets the last piece of cake?</h2>
<p>We're making progress. Whether we pass its arguments by name or positionally,
our call to <code>part</code> produces two partitions of the original list. And those
partitions now come back with convenient labels, that we can specify via
the optional <code>@labels</code> parameter.</p>
<p>But now there's a problem. Even though we explicitly marked it as
optional, it turns out that things can go horribly wrong if we don't
actually supply that optional argument. Which is not very &quot;optional&quot;. And,
worse, it means there's potentially a problem with every single legacy
call to <code>part</code> that was coded before we added the optional parameter.</p>
<p>For example, consider the call:</p>
<pre>    @pets = ('Canis latrans', 'Felis sylvestris');

    @parts = part /:i felis/, @pets;

    # expected to return: (sheep=&gt;['Felis sylvestris'], goats=&gt;['Canis latrans'] )
    # actually returns:   ('Felis sylvestris'=&gt;[], 'Canis latrans'=&gt;[])</pre>
<p>What went wrong?</p>
<p>Well, when the call to <code>part</code> is matching its argument list
against <code>&amp;call</code>'s parameter list, it works left-to-right as follows:</p>
<ul>
<li><a name='1.'></a>1.</li>
<p>The first parameter (<code>$is_sheep</code>) is declared as a scalar of type
<code>Selector</code>. So the first argument must be a <code>Code</code> or a <code>Class</code> or
a <code>Hash</code> or a <code>Rule</code>. It's actually a <code>Rule</code>, so the call mechanism
binds that rule to <code>$is_sheep</code>.</p>
<li><a name='2.'></a>2.</li>
<p>The second parameter (<code>?@labels</code>) is declared as an array of two
strings. So the second argument must be an array of two strings.
<code>@pets</code> is an array of two strings, so we bind that array to
<code>@labels</code>. (Oops!)</p>
<li><a name='3.'></a>3.</li>
<p>The third parameter (<code>*@data</code>) is declared as a slurpy array. So any
remaining arguments should be flattened and bound to successive elements
of <code>@data</code>. There are no remaining arguments, so there's nothing
to flatten-and-bind, so <code>@data</code> remains empty.</p>
</ul>
<p>And that's the problem. If we pass the arguments positionally, and there
are not enough of them to bind to every parameter, the parameters at the
start of the parameter list are bound before those towards the end. Even
if those earlier parameters are marked optional. In other words,
argument binding is &quot;greedy&quot; and (for obvious efficiency reasons) it
never backtracks to see if there might be better ways to match arguments
to parameters. Which means, in this case, that our data is being pre-emptively
&quot;stolen&quot; by our labels.</p>
<a name='Pipeline to the rescue!'></a><h2>Pipeline to the rescue!</h2>
<p>So in general (and in the above example in particular) we need some way
of indicating that a positional argument belongs to the slurpy data, not to
some preceding optional parameter. One way to do that is to pass the
ambiguous argument by name:</p>
<pre>    @parts = part /:i felis/, data=&gt;@pets;</pre>
<p>Then there can be no mistake about which argument belongs to what parameter.</p>
<p>But there's also a purely positional way to tell the call to <code>part</code>
that <code>@pets</code> belongs to the slurpy <code>@data</code>, not to the optional
<code>@labels</code>. We can pipeline it directly there. After all, that's
precisely what the pipeline operator does: it binds the list on its
blunt side to the slurpy array parameter of the call on its sharp side.
So we could just write:</p>
<pre>    @parts = part /:i felis/ &lt;== @pets;

    # returns: (sheep=&gt;['Felis sylvestris'], goats=&gt;['Canis latrans'])</pre>
<p>Because <code>@pets</code> now appears on the blunt end of a pipeline, there's no way it
can be interpreted as anything other than the slurped data for the call to
<code>part</code>.</p>
<a name='A natural assumption'></a><h2>A natural assumption</h2>
<p>Of course, as a solution to the problem of legacy code, this is highly
sub-optimal. It requires that every single pre-existing call to <code>part</code>
be modified (by having a pipeline inserted). And that will almost certainly
be too painful.</p>
<p>Our new optional labels would be much more useful if their existence
itself was also optional. If we could somehow add a single statement to
the start of any legacy code file and thereby cause <code>&amp;part</code> to work
like it used to in the good old days before labels. In other words, what
we really want is an imposter <code>&amp;part</code> subroutine that pretends that it
only has the original two parameters (<code>$is_sheep</code> and <code>@data</code>), but
then when it's called surreptitiously supplies an appropriate value for
the new <code>@label</code> parameter and quietly calls the real <code>&amp;part</code>.</p>
<p>And, in Perl 6, that's easy. All we need is a good curry.</p>
<p>We write the following at the start of the file:</p>
<pre>    use List::Part;   # Supposing &amp;part is defined in this module

    my &amp;part ::= &amp;List::Part::part.assuming(labels =&gt; &lt;&lt;sheep goats&gt;&gt;)</pre>
<p>That second line is a little imposing so let's break it down.
First of all:</p>
<pre>    List::Part::part</pre>
<p>is just the fully qualified name of the <code>&amp;part</code> subroutine that's defined in
the <code>List::Part</code> module (which, for the purposes of this example, is where
we're saying <code>&amp;part</code> lives). So:</p>
<pre>    &amp;List::Part::part</pre>
<p>is the actual <code>Code</code> object corresponding to the <code>&amp;part</code> subroutine. So:</p>
<pre>    &amp;List::Part::part.assuming(...)</pre>
<p>is a method call on that <code>Code</code> object. This is the tricky bit, but it's
no big deal really. If a <code>Code</code> object really is an
object, we certainly ought to be able to call methods on it. So:</p>
<pre>    &amp;List::Part::part.assuming(labels =&gt; &lt;&lt;sheep goats&gt;&gt;)</pre>
<p>calls the <code>assuming</code> method of the <code>Code</code> object <code>&amp;part</code> and passes the
<code>assuming</code> method a named argument whose name is <code>labels</code> and whose
value is the list of strings <code>&lt;&lt;sheep goats&gt;&gt;</code>.</p>
<p>Now, if we only knew what the <code>.assuming</code> method did...</p>
<a name='That about wraps it up'></a><h2>That about wraps it up</h2>
<p>What the <code>.assuming(...)</code> method does is place an anonymous wrapper
around an existing <code>Code</code> object and then return a reference to
(what appears to be) an entirely separate <code>Code</code> object. That new
<code>Code</code> object works exactly like the original &ndash; except that the new
one is missing one or more of the original's parameters.</p>
<p>Specifically, the parameter list of the wrapper subroutine doesn't have
any of the parameters that were named in in the call to <code>.assuming</code>.
Instead those missing parameters are automatically filled in whenever
the new subroutine is called, using the values of those named
arguments to <code>.assuming</code>.</p>
<p>All of which simply means that the method call:</p>
<pre>    &amp;List::Part::part.assuming(labels =&gt; &lt;&lt;sheep goats&gt;&gt;)</pre>
<p>returns a reference to a new subroutine that acts like this:</p>
<pre>    sub ($is_sheep, *@data) {
        return part($is_sheep, labels=&gt;&lt;&lt;sheep goats&gt;&gt;, *@data)
    }</pre>
<p>That is, because we passed a <code>labels =&gt; &lt;&lt;sheep goats&gt;&gt;</code>  argument
to <code>.assuming</code>, we get back a subroutine <i>without</i> a <code>labels</code>
parameter, but which then just calls <code>part</code> and inserts the value
<code>&lt;&lt;sheep goats&gt;&gt;</code>  for the missing parameter.</p>
<p>Or, as the code itself suggests:</p>
<pre>    &amp;List::Part::part.assuming(labels =&gt; &lt;&lt;sheep goats&gt;&gt;)</pre>
<p>gives us what <code>&amp;List::Part::part</code> would become under the assumption that
the value of <code>@labels</code> is always <code>&lt;&lt;sheep goats&gt;&gt;</code> .</p>
<p>How does that help with our source code backwards compatibility problem?
It completely solves it. All we have to do is to make Perl 6 use that
carefully wrapped, two-parameter version of <code>&amp;part</code> in all our legacy
code, instead of the full three-parameter one. And to do that we merely
create a lexical subroutine of the same name and bind the wrapped
version to that lexical:</p>
<pre>    my &amp;part ::= &amp;List::Part::part.assuming(labels =&gt; &lt;&lt;sheep goats&gt;&gt;);</pre>
<p>The <code>my &amp;part</code> declares a lexical subroutine named <code>&amp;part</code> (in exactly
the same way that a <code>my $part</code> would declare a lexical variable named
<code>$part</code>). The <code>my</code> keyword says that it's lexical and the sigil
says what kind of thing it is (<code>&amp;</code> for subroutine, in this case). Then
we simply install the wrapped version of <code>&amp;List::Part::part</code> as the
implementation of the new lexical <code>&amp;part</code> and we're done.</p>
<p>Just as lexical variables hide package or global variables of the same name,
so too a lexical subroutine hides any package or global subroutine of the same
name. So <code>my &amp;part</code> hides the imported <code>&amp;List::Part::part</code>, and every
subsequent call to <code>part(...)</code> in the rest of the current scope calls
the lexical <code>&amp;part</code> instead.</p>
<p>And, because that lexical version is bound to a label-assuming wrapper,
it doesn't have a <code>labels</code> parameter, so none of the legacy calls to
<code>&amp;part</code> are broken. Instead, the lexical <code>&amp;part</code> just silently &quot;fills
in&quot; the <code>labels</code> parameter with the value we originally gave to
<code>.assuming</code>.</p>
<p>And if we needed to add another partitioning call within the scope of that
lexical <code>&amp;part</code>, but we wanted to use those sexy new non-default labels, we
could do so by calling the actual three-parameter <code>&amp;part</code> via its fully
qualified name, like so:</p>
<pre>    @parts = List::Part::part(Animal::Cat, &lt;&lt;cat chattel&gt;&gt;, @animals);</pre>
<a name='Pair bonding'></a><h2>Pair bonding</h2>
<p>One major advantage of having <code>&amp;part</code> return a list of pairs rather than a
simple list of arrays is that now, instead of positional binding:</p>
<pre>    # with original (list-of-arrays) version of &amp;part...
    (@cats, @chattels) := part Animal::Cat &lt;== @animals;</pre>
<p>we can do &quot;named binding&quot;</p>
<pre>    # with latest (list-of-pairs) version of &amp;part...
    (goats=&gt;@chattels, sheep=&gt;@cats) := part Animal::Cat &lt;== @animals;</pre>
<p>Named binding???</p>
<p>Well, we <i><a href='#Name your poison'>just learned</a></i> that we can bind arguments to
parameters by name.  But <i><a href='#In a bind'>earlier we saw</a></i> that parameter
binding is merely an implicit form of explicit <code>:=</code> binding.
So the inevitable conclusion is that the only reason we can bind parameters by
name is because <code>:=</code> supports named binding.</p>
<p>And indeed it does. If a <code>:=</code> finds a list of pairs on its right-hand side,
and a list of simple variables on its left-hand side, it uses named
binding instead of positional binding. That is, instead of binding first
to first, second to second, etc., the <code>:=</code> uses the key of each right-
hand pair to determine the name of the variable on its left to which the
value of the pair should be bound.</p>
<p>That sounds complicated, but the effect is very easy to understand:</p>
<pre>    # Positional binding...
    ($who, $why) := ($because, &quot;me&quot;);
    # same as: $who := $because; $why := &quot;me&quot;;

    # Named binding...
    ($who, $why) := (why =&gt; $because, who =&gt; &quot;me&quot;);
    # same as: $who := &quot;me&quot;; $why := $because;</pre>
<p>Even more usefully, if the binding operator detects a list of pairs on its
left and another list of pairs on its right, it binds the value of the first
pair on the right to the value of the identically named pair on the
left (again, regardless of where the two pairs appear in their respective
lists). Then it binds the value of the second pair on the right to the
value of the identically named pair on the left, and so on.</p>
<p>That means we can set up a named <code>:=</code> binding in which the names of the
bound variables don't even have to match the keys of the values being
bound to them:</p>
<pre>    # Explicitly named binding...
    (who=&gt;$name, why=&gt;$reason) := (why =&gt; $because, who =&gt; &quot;me&quot;);
    # same as: $name := &quot;me&quot;; $reason := $because;</pre>
<p>The most common use for that feature will probably be to create &quot;free-standing&quot;
aliases for particular entries in a hash:</p>
<pre>    (who=&gt;$name, why=&gt;$reason) := *%explanation;
    # same as: $name := %explanation{who}; $reason := %explanation{why};</pre>
<p>or to convert particular hash entries into aliases for other variables:</p>
<pre>    *%details := (who=&gt;&quot;me&quot;, why=&gt;$because);
    # same as: %details{who} := &quot;me&quot;, %details{why} := $because;</pre>
<a name='An argument in name only'></a><h1>An argument in name only</h1>
<p>It's pretty cool that Perl 6 automatically lets us specify positional
arguments &ndash; and even return values &ndash; by name rather than position.</p>
<p>But what if we'd prefer that some of our arguments could <i>only</i> be
specified by name. After all, the <code>@labels</code> parameter isn't really in
the same league as the <code>$is_sheep</code> parameter: it's only an option after
all, and one that most people probably won't use. It shouldn't really
be a positional parameter at all.</p>
<p>And we <b>can</b> specify that the <code>labels</code> argument is only to be passed
by name...by changing the <i><a href='#A label by any other name'>previous declaration</a></i>
of the <code>@labels</code> parameter very slightly:</p>
<pre>    sub part (Selector $is_sheep,
              Str +@labels is dim(2) = &lt;&lt;sheep goats&gt;&gt;,
              *@data
             ) returns List of Pair
    {
        my ($sheep, $goats) is constant = @labels;
        my %herd = ($sheep=&gt;[], $goats=&gt;[]);
        for @data {
            when $is_sheep { push %herd{$sheep}, $_ }
            default        { push %herd{$goats}, $_ }
        }
        return *%herd;
    }</pre>
<p>In fact, there's only a single character's worth of difference in the
whole definition. Whereas before we declared the <code>@labels</code> parameter
like this:</p>
<pre>       Str ?@labels is dim(2) = &lt;&lt;sheep goats&gt;&gt;</pre>
<p>now we declare it like this:</p>
<pre>       Str +@labels is dim(2) = &lt;&lt;sheep goats&gt;&gt;</pre>
<p>Changing that <code>?</code> prefix to a <code>+</code> changes <code>@labels</code> from an optional
positional-or-named parameter to an optional named-only parameter. So
now if we want to pass in a <code>labels</code> argument, we can only pass it by
name. Attempting to pass it positionally will result in some extreme
prejudice from the compiler.</p>
<p>Named-only parameters are still optional parameters however, so legacy code
that omits the labels:</p>
<pre>    %parts = part Animal::Cat &lt;== @animals;</pre>
<p>still works fine (and still causes the <code>@labels</code> parameter to default to
<code>&lt;&lt;sheep goats&gt;&gt;</code>).</p>
<p>Better yet, converting <code>@labels</code> from a positional to a named-only
parameter also solves the problem of legacy code of the form:</p>
<pre>    %parts = part Animals::Cat, @animals;   </pre>
<p><code>@animals</code> can't possibly be intended for the <code>@labels</code>
parameter now. We explicitly specified that labels can only be passed by
name, and the <code>@animals</code> argument isn't named.</p>
<p>So named-only parameters give us a clean way of upgrading a subroutine
and still supporting legacy code. Indeed, in many cases the <b>only</b>
reasonable way to add a new parameter to an existing, widely used, Perl
6 subroutine will be to add it as a named-only parameter.</p>
<p>[Update: Named parameters are now marked with <code>:</code> instead of <code>+</code>.]</p>
<a name='Careful with that arg, Eugene!'></a><h1>Careful with that arg, Eugene!</h1>
<p>Of course, there's no free lunch here. The cost of solving the legacy code
problem is that we changed the meaning of any more recent code like this:</p>
<pre>    %parts = part Animal::Cat, &lt;&lt;cat chattel&gt;&gt;, @animals;     # Oops!</pre>
<p>When <code>@labels</code> was positional-or-named, the <code>&lt;&lt;cat chattel&gt;&gt;</code>
argument could only be interpreted as being intended for
<code>@labels</code>. But now, there's no way it can be for <code>@labels</code> (because
it isn't named), so Perl 6 assumes that the list is just part of the
slurped data. The two-element list will now be flattened (along with
<code>@animals</code>), resulting in a single list that is then bound to the <code>@data</code>
parameter. As if we'd written:</p>
<pre>    %parts = part Animal::Cat &lt;== 'cat', 'chattel', @animals;</pre>
<p>This is yet another reason why named-only should probably be the first
choice for optional parameters.</p>
<a name='Temporal life insurance'></a><h2>Temporal life insurance</h2>
<p>Being able to add name-only parameters to existing subroutines
is an important way of future-proofing any calls to the subroutine. So
long as we continue to add only named-only parameters to <code>&amp;part</code>, the order
in which the subroutine expects its positional and slurpy arguments will
be unchanged, so every existing call to <code>part</code> will
continue to work correctly.</p>
<p>And, curiously, the reverse is also true. Named-only parameters also
provide us with a way to &quot;history-proof&quot; subroutine <i>calls</i>. That is,
we can allow a subroutine to accept named arguments that it doesn't
(yet) know how to handle! Like so:</p>
<pre>    sub part (Selector $is_sheep,
              Str +@labels is dim(2) = &lt;&lt;sheep goats&gt;&gt;
              *%extras,         # &lt;-- NEW PARAMETER ADDED HERE
              *@data,
             ) returns List of Pair
    {
        # Handle extras...
        carp &quot;Ignoring unknown named parameter '$_'&quot; for keys %extras;

        # Remainder of subroutine as before...
        my ($sheep, $goats) is constant = @labels;
        my %herd = ($sheep=&gt;[], $goats=&gt;[]);
        for @data {
            when $is_sheep { push %herd{$sheep}, $_ }
            default        { push %herd{$goats}, $_ }
        }
        return *%herd;
    }

    # and later...

    %parts = part Animal::Cat, label=&gt;&lt;&lt;Good Bad&gt;&gt;, max=&gt;3, @data;

    # warns: &quot;Ignoring unknown parameter 'max' at future.pl, line 19&quot;</pre>
<p>The <code>*%extras</code> parameter is a &quot;slurpy hash&quot;. Just as the slurpy array
parameter (<code>*@data</code>) sucks up any additional positional arguments for
which there's no explicit parameter, a slurpy hash sucks up any
named arguments that are unaccounted for. In the above example, for
instance, <code>&amp;part</code> has no <code>$max</code> parameter, so passing the named
argument <code>max=&gt;3</code> would normally produce a (compile-time)
exception:</p>
<pre>    Invalid named parameter ('max') in call to &amp;part</pre>
<p>However, because <code>&amp;part</code> now has a slurpy hash, that extraneous named
argument is simply bound to the appropriate entry of <code>%extras</code> and
(in this example) used to generate a warning.</p>
<p>The more common use of such slurpy hashes is to capture the named
arguments that are passed to an object constructor and have them
automatically forwarded to the constructors of the appropriate
ancestral classes. We'll explore that technique in Exegesis 12.</p>
<a name='The greatest thing since sliced arrays'></a><h1>The greatest thing since sliced arrays</h1>
<p>So far we've progressively extended <code>&amp;part</code> from the first simple version
that only accepted subroutines as selectors, to the most recent versions
that can now also use classes, rules, or hashes to partition their data.</p>
<p>Suppose we also wanted to allow the user to specify a list of integer
indices as the selector, and thereby allow <code>&amp;part</code> to separate a slice of
data from its &quot;antislice&quot;. In other words, instead of:</p>
<pre>    %data{2357}  = [ @data[2,3,5,7]            ];
    %data{other} = [ @data[0,1,4,6,<a href='mailto:8..@data-1'>8..@data-1</a>] ];</pre>
<p>we could write:</p>
<pre>    %data = part [2,3,5,7], labels=&gt;[&quot;2357&quot;,&quot;other&quot;], @data;</pre>
<p>We could certainly extend <code>&amp;part</code> to do that:</p>
<pre>    type Selector ::= Code | Class | Rule | Hash | (Array of Int);

    sub part (Selector $is_sheep,
              Str +@labels is dim(2) = &lt;&lt;sheep goats&gt;&gt;,
              *@data
             ) returns List of Pair
    {
        my ($sheep, $goats) is constant = @labels;
        my %herd = ($sheep=&gt;[], $goats=&gt;[]);
        if $is_sheep.isa(Array of Int) {
            for @data.kv -&gt; $index, $value {
                if $index == any($is_sheep) { push %herd{$sheep}, $value }
                else                        { push %herd{$goats}, $value }
            }
        }
        else {
            for @data {
                when $is_sheep { push %herd{$sheep}, $_ }
                default        { push %herd{$goats}, $_ }
            }
        }
        return *%herd;
    }

    # and later, if there's a prize for finishing 1st, 2nd, 3rd, or last...

    %prize = part [0, 1, 2, @horses-1],
                  labels =&gt; &lt;&lt; placed  also_ran &gt;&gt;,
                  @horses;</pre>
<p>Note that this is the first time we couldn't just add another class
to the <code>Selector</code> type and rely on the smart-match inside the <code>when</code>
to work out how to tell &quot;sheep&quot; from &quot;goats&quot;. The problem here is that when
the selector is an array of integers, the <i>value</i> of each data element no
longer determines its sheepishness/goatility. It's now the element's
<i>position</i> (i.e. its index) that decides its fate. And, since our
existing smart-match compares values, not positions, the <code>when</code> can't
pick out the right elements for us. Instead, we have to consider both
the index <i>and</i> the value of each data element.</p>
<p>To do that we use the <code>@data</code> array's <code>.kv</code> method. Just as
calling the <code>.kv</code> method on a hash returns <i>key</i>, <i>value</i>, <i>key</i>,
<i>value</i>, <i>key</i>, <i>value</i>, etc., so too calling the <code>.kv</code> method on an
array returns <i>index</i>, <i>value</i>, <i>index</i>, <i>value</i>, <i>index</i>,
<i>value</i>, etc. Then we just use a parameterized block as our <code>for</code>
block, specifying that it has two arguments. That causes the <code>for</code> to
grab two elements of the list its iterating (i.e. one index and one
value) on each iteration.</p>
<p>Then we simply test to see if the current index is any of those specified in
<code>$is_sheep</code>'s array and, if so, we push the corresponding value:</p>
<pre>    for @data.kv -&gt; $index, $value {
        if $index == any(@$is_sheep) { push %herd{$sheep}, $value }
        else                         { push %herd{$goats}, $value }
    }</pre>
<a name='A parting of the...err...parts'></a><h1>A parting of the...err...parts</h1>
<p>That works okay, but it's not perfect. In fact, as it's presented above
the <code>&amp;part</code> subroutine is now both an ugly solution and an inefficient one.</p>
<p>It's ugly because <code>&amp;part</code> is now twice as long as it was
before. And the two branches of control-flow within it are similar in
form but quite different in function. One partitions the data according
to the <i>contents</i> of a datum; the other, according to a datum's
<i>position</i> in <code>@data</code>.</p>
<p>It's inefficient because it effectively tests the type of the selector
argument twice: once (implicitly) when it's first bound to the
<code>$is_sheep</code> parameter, and then again (explicitly) in the call to
<code>.isa</code>.</p>
<p>It would be cleaner and more maintainable to break these two nearly unrelated
behaviours out into separate subroutines. And it would be more efficient if
we could select between those two subroutines by testing the type of the
selector only once.</p>
<p>And, of course, in Perl 6 we can do just that &ndash; with a <i>multisub</i>.</p>
<p>What's a multisub? It's a collection of related subroutines (known as
&quot;variants&quot;), all of which have the same name but different parameter
lists. When the multisub is called and passed a list of arguments, Perl
6 examines the types of the arguments, finds the variant with the same
name and the most compatible parameter list, and calls that variant.</p>
<p>By the way, you might be more familiar with the term <i>multimethod</i>.
A multisub is a multiply dispatched subroutine, in the same way that
a multimethod is a multiply dispatched method. There'll be much more
about those in Exegesis 12.</p>
<p>Multisubs provide facilities something akin to function overloading in
C++. We set up several subroutines with the same logical name (because
they implement the same logical action). But each takes a distinct set
of argument types and does the appropriate things with those particular
arguments.</p>
<p>However, multisubs are more &quot;intelligent&quot; that mere overloaded
subroutines. With overloaded subroutines, the compiler examines the
compile-time types of the subroutine's arguments and hard-codes a call
to the appropriate variant based on that information. With multisubs,
the compiler takes no part in the variant selection process. Instead,
the interpreter decides which variant to invoke at the time the call is
actually made. And it does that by examining the <i>run-time</i> type of
each argument, making use of its inheritance relationships to resolve
any ambiguities.</p>
<p>To see why a run-time decision is better, consider the following code:</p>
<pre>    class Lion is Cat {...}    # Lion inherits from Cat

    multi sub feed(Cat  $c) { pat $c; my $glop = open 'Can'; spoon_out($glop); }
    multi sub feed(Lion $l) { $l.stalk($prey) and kill; }

    my Cat $fluffy = Lion.new;

    feed($fluffy);</pre>
<p>In Perl 6, the call to <code>feed</code> will correctly invoke the second variant
because the interpreter knows that <code>$fluffy</code> actually contains a reference
to a <code>Lion</code> object at the time the call is made (even though the nominal type
of the variable is <code>Cat</code>).</p>
<p>If Perl 6 multisubs worked like C++'s function overloading,
the call to <code>feed($fluffy)</code> would invoke the <i>first</i> version of
<code>feed</code>, because all that the compiler knows for sure at compile-time is
that <code>$fluffy</code> is declared to store <code>Cat</code> objects.
And that's precisely why Perl 6 doesn't do it that way. We prefer leave the
hand-feeding of lions to other languages.</p>
<a name='Many parts'></a><h2>Many parts</h2>
<p>As the above example shows, in Perl 6, multisub variants are defined
by prepending the <code>sub</code> keyword with another keyword: <code>multi</code>.
The parameters that the interpreter is going to consider when deciding
which variant to call are specified to the left of a colon (<code>:</code>), with
any other parameters specified to the right. If there is no colon in the
parameter list (as above), <i>all</i> the parameters are considered when
deciding which variant to invoke.</p>
<p>So we could refactor the
<i><a href='#The greatest thing since sliced arrays'>most recent version of <code>&amp;part</code></a></i>
like so:</p>
<pre>    type Selector ::= Code | Class | Rule | Hash;

    multi sub part (Selector $is_sheep:
                    Str +@labels is dim(2) = &lt;&lt;sheep goats&gt;&gt;,
                    *@data
                   ) returns List of Pair
    {
        my ($sheep, $goats) is constant = @labels;
        my %herd = ($sheep=&gt;[], $goats=&gt;[]);
        for @data {
            when $is_sheep { push %herd{$sheep}, $_ }
            default        { push %herd{$goats}, $_ }
        }
        return *%herd;
    }


    multi sub part ( Int @sheep_indices:
                 Str +@labels is dim(2) = &lt;&lt;sheep goats&gt;&gt;,
                 *@data
           ) returns List of Pair
    {
        my ($sheep, $goats) is constant = @labels;
        my %herd = ($sheep=&gt;[], $goats=&gt;[]);
        for @data -&gt; $index, $value {
            if $index == any(@sheep_indices) { push %herd{$sheep}, $value }
            else                             { push %herd{$goats}, $value }
        }
        return *%herd;
    }</pre>
<p>Here we create two variants of a single multisub named <code>&amp;part</code>. The first
variant will be invoked whenever <code>&amp;part</code> is called with a <code>Selector</code>
object as its first argument (that is, when it is passed a <code>Code</code> or
<code>Class</code> or <code>Rule</code> or <code>Hash</code> object as its selector).</p>
<p>The second variant will be invoked only if the first argument is an
<code>Array of Int</code>. If the first argument is anything else, an exception
will be thrown.</p>
<p>Notice how similar the body of the first variant is to the earlier
subroutine versions. Likewise, the body of the second variant is
almost identical to the <code>if</code> branch of the
<i><a href='#The greatest thing since sliced arrays'>previous (subroutine) version</a></i>.</p>
<p>Notice too how the body of each variant only has to deal with the
particular type of selector that its first parameter specifies.
That's because the interpreter has already determined what type of thing
the first argument was when deciding which variant to call. So a
particular variant will only ever be called if the first argument is
compatible with that variant's first parameter.</p>
<a name='Call me early'></a><h1>Call me early</h1>
<p>Suppose we wanted more control over the default labels that <code>&amp;part</code> uses
for its return values. For example, suppose we wanted to be able to
prompt the user for the appropriate defaults &ndash; before the program runs.</p>
<p>The default value for an optional parameter can be any valid Perl expression
whose result is compatible with the type of the parameter. So we could
simply write:</p>
<pre>    my Str @def_labels;

    BEGIN {
        print &quot;Enter 2 default labels: &quot;;
        @def_labels = split(/\s+/, &lt;&gt;, 3).[0..1];
    }

    sub part (Selector $is_sheep,
              Str +@labels is dim(2) = @def_labels,
              *@data
             ) returns List of Pair
    {
        # body as before
    }</pre>
<p>We first define an array variable:</p>
<pre>    my Str @def_labels;</pre>
<p>This will ultimately serve as the expression that the <code>@labels</code> parameter
uses as its default:</p>
<pre>       Str +@labels is dim(2) = @def_labels</pre>
<p>Then we merely need a <code>BEGIN</code> block (so that it runs before the program
starts) in which we prompt for the required information:</p>
<pre>    print &quot;Enter 2 default labels: &quot;;</pre>
<p>read it in:</p>
<pre>    &lt;&gt;</pre>
<p>split the input line into three pieces using whitespace as a separator:</p>
<pre>    split(/\s+/, &lt;&gt;, 3)</pre>
<p>grab the first two of those pieces:</p>
<pre>    split(/\s+/, &lt;&gt;, 3).[0..1]</pre>
<p>and assign them to <code>@def_labels</code>:</p>
<pre>    @def_labels = split(/\s+/, &lt;&gt;, 3).[0..1];</pre>
<p>So we're guaranteed that <code>@def_labels</code> has the necessary default labels before
<code>&amp;part</code> is ever called.</p>
<a name='Core breach'></a><h2>Core breach</h2>
<p>Builtins like <code>&amp;split</code> can also be given named arguments in Perl 6 so,
alternatively, we could write the <code>BEGIN</code> block like so:</p>
<pre>    BEGIN {
        print &quot;Enter 2 default labels: &quot;;
        @def_labels = split(str=&gt;&lt;&gt;, max=&gt;3).[0..1];
    }</pre>
<p>Here we're leaving out the split pattern entirely and making use of
<code>&amp;split</code>'s default split-on-whitespace behaviour.</p>
<p>Incidentally, an important goal of Perl 6 is to make the language powerful
enough to natively implement all its own builtins. No, we won't actually
implement it that way, since screamingly fast performance is another
goal. But we do want to make it easy for anyone to create their own
versions of any Perl built-in or control structure.</p>
<p>So, for example, <code>&amp;split</code> would be declared like this:</p>
<pre>    sub split( Rule|Str ?$sep = /\s+/,
                    Str ?$str = $CALLER::_,
                    Int ?$max = Inf
             )
    {
        # implementation here
    }</pre>
<p>Note first that every one of <code>&amp;split</code>'s parameters is optional, and that the
defaults are the same as in Perl 5. If we omit the separator pattern, the
default separator is whitespace; if we omit the string to be split, <code>&amp;split</code>
splits the caller's <code>$_</code> variable; if we omit the &quot;maximum number of
pieces to return&quot; argument, there is no upper limit on the number of
splits that may be made.</p>
<p>Note that we can't just declare the second parameter like so:</p>
<pre>    Str ?$str = $_,</pre>
<p>That's because, in Perl 6, the <code>$_</code> variable is lexical (not global), so
a subroutine doesn't have direct access to the <code>$_</code> of its caller.
That means that Perl 6 needs a special way to access a caller's <code>$_</code>.</p>
<p>That special way is via the <code>CALLER::</code> namespace. Writing <code>$CALLER::_</code>
gives us access to the <code>$_</code> of whatever scope called the current
subroutine. This works for other variables too (<code>$CALLER::foo</code>,
<code>@CALLER::bar</code>, etc.) but is rarely useful, since we're only allowed to
use <code>CALLER::</code> to access variables that already exist, and <code>$_</code> is
about the only variable that a subroutine can rely upon to be present in
any scope it might be called from.</p>
<a name='A constant source of joy'></a><h2>A constant source of joy</h2>
<p>Setting up the <code>@def_labels</code> array at compile-time and then using it as the
default for the <code>@labels</code> parameter works fine, but there's always
the chance that the array might somehow be accidentally reassigned later.
If that's not desirable, then we need to make the array a constant. In
Perl 6 that looks like this:</p>
<pre>    my @def_labels is constant = BEGIN {
        print &quot;Enter 2 default labels: &quot;;
        split(/\s+/, &lt;&gt;, 3).[0..1];
    };</pre>
<p>[Update: Now &quot;<code>constant @def_labels = ...</code>&quot; does that.  The corresponding
trait is &quot;<code>readonly</code>&quot; for things that we're only pretending are constant.]</p>
<p>The <code>is constant</code> trait is the way we prevent any Perl 6 variable from
being reassigned after it's been declared. It effectively replaces the
<code>STORE</code> method of the variable's implementation with one that throws an
exception whenever it's called. It also instructs the compiler to keep
an eye out for compile-time-detectable modifications to the variable and
die violently if it finds any.</p>
<p>Whenever a variable is declared <code>is constant</code> it must be initialized as
part of its declaration. In this case we use the return value of a
<code>BEGIN</code> block as the initializer value.</p>
<p>Oh, by the way, <code>BEGIN</code> blocks have return values in Perl 6.
Specifically, they return the value of the last statement executed
inside them (just like a Perl 5 <code>do</code> or <code>eval</code> block does, except that
<code>BEGIN</code>s do it at compile-time).</p>
<p>In the above example the result of the <code>BEGIN</code> is the return value of
the call to <code>split</code>.  So <code>@def_labels</code> is initialized to the two default
labels, which cannot thereafter be changed.</p>
<a name='BEGIN at the scene of the crime'></a><h2><code>BEGIN</code> at the scene of the crime</h2>
<p>Of course, the <code>@def_labels</code> array is really just a temporary storage
facility for transferring the results of the <code>BEGIN</code> block to the default
value of the <code>@labels</code> parameter.</p>
<p>We could easily do away with it entirely, by simply putting the <code>BEGIN</code> block
right there <i>in</i> the parameter list:</p>
<pre>
    sub part (Selector $is_sheep,
              Str +@labels is dim(2) = BEGIN {
                          print &quot;Enter 2 default labels: &quot;; 
                          split(/\s+/, &lt;&gt;, 3).[0..1];
                        },
              *@data
             ) returns List of Pair
    {
        # body as before
    }</pre>
<p>And that works fine.</p>
<a name='Macro biology'></a><h1>Macro biology</h1>
<p>The only problem is that it's ugly, brutish, and not at all
short. If only there were some way of calling the <code>BEGIN</code> block at that
point without having to put the actual <code>BEGIN</code> block at that point.</p>
<p>Well, of course there is such a way. In Perl 6 a block is just a special
kind of nameless subroutine...and a subroutine is just a special name-ful
kind of block. So it shouldn't really come as a surprise that <code>BEGIN</code>
blocks have a name-ful, subroutine-ish counterpart.
They're called <i>macros</i> and they look and act very much like ordinary
subroutine, except that they run at compile-time.</p>
<p>So, for example, we could create a compile-time subroutine that requests and
returns our user-specified labels:</p>
<pre>    macro request(int $n, Str $what) returns List of Str {
        print &quot;Enter $n $what: &quot;;
        my @def_labels = split(/\s+/, &lt;&gt;, $n+1);
        return { @def_labels[0..$n-1] };
    }

    # and later...

    sub part (Selector $is_sheep,
              Str +@labels is dim(2) = request(2,&quot;default labels&quot;),
              *@data
             ) returns List of Pair
    {
        # body as before
    }</pre>
<p>Calls to a macro are invoked during compilation (not at run-time). In
fact, like a <code>BEGIN</code> block, a macro call is executed as soon as the
parser has finished parsing it. So, in the above example, when the
parser has parsed the declaration of the <code>@labels</code> parameter and then
the <code>=</code> sign indicating a default value, it comes across what looks
like a subroutine call. As soon as it has parsed that subroutine call
(including its argument list) it will detect that the subroutine
<code>&amp;request</code> is actually a macro, so it will immediately call <code>&amp;request</code>
with the specified arguments (<code>2</code> and <code>&quot;default labels&quot;</code>).</p>
<p>Whenever a macro like <code>&amp;request</code> is invoked, the parser itself intercepts
the macro's return value and integrates it somehow back into the parse
tree it is in the middle of building. If the macro returns a block &ndash; as
<code>&amp;request</code> does in the above example &ndash; the parser extracts the
the contents of that block and inserts the parse tree of those contents
into the program's parse tree. In other words, if a macro returns a
block, a precompiled version of whatever is inside the block replaces
the original macro call.</p>
<p>[Update: Now we use a <code>code</code> declaration on the block, which turns it into
a quasiquote that returns an AST, and enables unquasiquoting inside.]</p>
<p>Alternatively, a macro can return a string. In which case, the parser
inserts that string back into the source code in place of the macro
call and then reparses it. Which means we could also write <code>&amp;request</code>
like this:</p>
<pre>    macro request(int $n, Str $what) returns List of Str {
        print &quot;Enter $n $what: &quot;;
        return &quot;&lt;&lt; ( @(split(/\s+/, &lt;&gt;, $n+1).[0..$n-1]) &gt;&gt;&quot;;
    }</pre>
<p>In which case it would return a string containing the characters
<code>&quot;&lt;&lt;&quot;</code>, followed by the two labels that the <code>request</code> call reads
in, followed by a closing double angles. The parser would then
substitute that string in place of the macro call, discover it was a
<code>&lt;&lt;...&gt;&gt;</code> word list, and use that list as the default labels.</p>
<a name='Macros for BEGIN-ers'></a><h2>Macros for <code>BEGIN</code>-ers</h2>
<p>Macros are enormously powerful. In fact, in Perl 6, we could implement
the functionality of <code>BEGIN</code> itself using a macro:</p>
<pre>    macro MY_BEGIN (&amp;block) {
        my $context = want;
        if $context ~~ List {
            my @values = block();
            return { *@values };
        }
        elsif $context ~~ Scalar {
            my $value = block();
            return { $value };
        }
        else {
            block();
            return;
        }
    }</pre>
<p>The <code>MY_BEGIN</code> macro declares a single parameter (<code>&amp;block</code>). Because
that parameter is specified with the <code>Code</code> sigil (<code>&amp;</code>), the macro
requires that the corresponding argument must be a block or subroutine
of some type. Within the body of <code>&amp;MY_BEGIN</code> that argument is bound to
the <i>lexical</i> subroutine <code>&amp;block</code> (just as a <code>$foo</code> parameter would
bind its corresponding argument to a lexical scalar variable, or a
<code>@foo</code> parameter would bind its argument to a lexical array).</p>
<p><code>&amp;MY_BEGIN</code> then calls the <code>want</code> function, which is Perl 6's
replacement for <code>wantarray</code>. <code>want</code> returns a scalar value that
simultaneously represents any the contexts in which the current
subroutine was called. In other words, it returns a disjunction of
various classes. We then compare that context information against the
three possibilities &ndash; <code>List</code>, <code>Scalar</code>, and (by elimination) <code>Void</code>.</p>
<p>If <code>MY_BEGIN</code> was called in a list context, we evaluate its
block/closure argument in a list context, capture the results in an
array (<code>@values</code>), and then return a block containing the contents of
that array flattened back to a list. In a scalar context we do much the
same thing, except that <code>MY_BEGIN</code>'s argument is evaluated in scalar
context and a block containing that scalar result is returned. In a void
context (the only remaining possibility), the argument is simply
evaluated and nothing is returned.</p>
<p>In the first two cases, returning a block causes the original macro call
to be replaced by a parse tree. Specifically, by the parse tree
representing the values that resulted from executing the original
block passed to <code>MY_BEGIN</code>.</p>
<p>In the final case &ndash; a void context &ndash; the compiler isn't expecting to
replace the macro call with anything, so it doesn't matter what we
return, just as long as we evaluate the block. The macro call itself is
simply eliminated from the final parse-tree.</p>
<p>Note that <code>MY_BEGIN</code> could be written more concisely than it was above,
by taking advantage of the smart-matching behaviour of a switch
statement:</p>
<pre>    macro MY_BEGIN (&amp;block) {
        given want {
            when List   { my @values = block(); return { *@values }; }
            when Scalar { my $value  = block(); return {  $value  }; }
            when Void   {              block(); return               }
        }
    }</pre>
<a name='A macro by any other syntax...'></a><h2>A macro by any other syntax...</h2>
<p>Because macros are called by the parser, it's possible to have them
interact with the parser itself. In particular, it's possible for a macro to
tell the parser how the macro's own argument list should be parsed.</p>
<p>For example, we could give the <code>&amp;request</code> macro its own non-standard
argument syntax, so that instead of calling it as:</p>
<pre>    request(2,&quot;default labels&quot;)</pre>
<p>we could just write:</p>
<pre>    request(2 default labels)</pre>
<p>To do that we'd define <code>&amp;request</code> like so:</p>
<pre>    macro request(int $n, Str $what) 
        is parsed( /:w \( (\d+) (.*?) \) / )
        returns List of Str
    {
        print &quot;Enter $n $what: &quot;;
        my @def_labels = split(/\s+/, &lt;&gt;, $n+1);
        return { @def_labels[0..$n-1] };
    }</pre>
<p>The <code>is parsed</code> trait tells the parser what to look for immediately after it
encounters the macro's name. In the above example, the parser is told that,
after encountering the sequence <code>&quot;request&quot;</code> it should expect to match the
pattern:</p>
<pre>    / :w        # Allow whitespace between the tokens
      \(        # Match an opening paren
      (\d+)     # Capture one-or-more digits
      (.*?)     # Capture everything else up to...
      \)        # ...a closing paren
    /</pre>
<p>Note that the one-or-more-digits and the anything-up-to-paren bits of the
pattern are in capturing parentheses. This is important because the
list of substrings that an <code>is parsed</code> pattern captures is then used
as the argument list to the macro call. So the captured digits become the
first argument (which is then bound to the <code>$n</code> parameter) and the captured
&quot;everything else&quot; becomes the second argument (and is bound to <code>$what</code>).</p>
<p>Normally, of course, we don't need to specify the <code>is parsed</code> trait when
setting up a macro. Since a macro is a kind of subroutine, by default
its argument list is parsed the same as any other subroutine's &ndash; as a
comma-separated list of Perl 6 expressions.</p>
<a name='Refactoring parameter lists'></a><h1>Refactoring parameter lists</h1>
<p>By this stage, you might be justified in feeling that <code>&amp;part</code>'s
parameter list is getting just a leeeeettle too sophisticated for its
own good. Moreover, if we were using the multisub version, that
complexity would have to be repeated in every variant.</p>
<p>Philosophically though, that's okay. The later versions of <code>&amp;part</code> are
doing some fairly sophisticated things, and the complexity required to
achieve that has to go somewhere. Putting that extra complexity in the
parameter list means that the body of <code>&amp;part</code> stays much simpler. As do
any calls to <code>&amp;part</code>.</p>
<p>Which is the whole point: <i>Complexify locally to simplify globally.</i>
Or maybe: <i>Complexify declaratively to simplify procedurally.</i></p>
<p>But there's precious little room for the consolations of philosophy when
you're swamped in code and up to your assembler in allomorphism.
So, rather than having to maintain those complex and repetitive parameter
lists, we might prefer to factor out the common infrastructure.
With, of course, yet another macro:</p>
<pre>    macro PART_PARAMS {
           my ($sheep,$goats) = request(2 default labels);
           return &quot;Str +\@labels is dim(2) = &lt;&lt;$sheep $goats&gt;&gt;, *\@data&quot;;
    }

    multi sub part (Selector $is_sheep, PART_PARAMS) {
        # body as before
    }

    multi sub part (Int @is_sheep, PART_PARAMS) {
        # body as before
    }</pre>
<p>Here we create a macro named <code>&amp;PART_PARAMS</code> that requests and extracts
the default labels and then interpolates them into a string, which it returns.
That string then replaces the original macro call.</p>
<p>Note that we reused the <code>&amp;request</code> macro within the <code>&amp;PART_PARAMS</code> macro.
That's important, because it means that, as the body of <code>&amp;PART_PARAMS</code>
is itself being parsed, the default names are requested and interpolated
into <code>&amp;PART_PARAMS</code>'s code. That ensures that the user-supplied
default labels are hardwired into <code>&amp;PART_PARAMS</code> even before it's
compiled. So every subsequent call to <code>PART_PARAMS</code> will return the
same default labels.</p>
<p>On the other hand, if we'd written <code>&amp;PART_PARAMS</code> like this:</p>
<pre>    macro PART_PARAMS {
           print &quot;Enter 2 default labels: &quot;;
           my ($sheep,$goats) = split(/\s+/, &lt;&gt;, 3);
           return &quot;*\@data, Str +\@labels is dim(2) = &lt;&lt;$sheep $goats&gt;&gt;&quot;;
    }</pre>
<p>then each time we used the <code>&amp;PART_PARAMS</code> macro in our code, it would
re-prompt for the labels. So we could give each variant of <code>&amp;part</code> it's
own default labels. Either approach is fine, depending on the effect we
want to achieve. It's really just a question how much work we're willing
to put in in order to be Lazy.</p>
<a name='Smooth operators'></a><h1>Smooth operators</h1>
<p>By now it's entirely possible that your head is spinning with the sheer number
of ways Perl 6 lets us implement the <code>&amp;part</code> subroutine. Each of those ways
represents a different tradeoff in power, flexibility, and maintainability of
the resulting code. But it's important to remember that, however we choose to
implement <code>&amp;part</code>, it's always invoked in basically the same way:</p>
<pre>    %parts = part $selector, @data;</pre>
<p>Sure, some of the above techniques let us modify the return labels, or
control the use of named vs positional arguments. But with all of them,
the call itself starts with the name of the subroutine, after which we
specify the arguments.</p>
<p>So let's change that too!</p>
<p>Suppose we preferred to have a partitioning <i>operator</i>, rather than a
subroutine. If we ignore those optional labels, and restrict our list to be an
actual array, we can see that the core partitioning operation is binary
(&quot;apply this selector to that array&quot;).</p>
<p>So if <code>&amp;part</code> is to become an operator, we need it to be a binary
operator. In Perl 6 we can make up completely new operators, so let's
take our partitioning inspiration from Moses and call our new operator: <code>~|_|~</code></p>
<p>We'll assume that this &quot;Red Sea&quot; operator is to be used like this:</p>
<pre>    %parts = @animals ~|_|~ Animal::Cat;</pre>
<p>That is, the left operand is the array to be partitioned, and the right
operand is the selector.  In which case, to implement it we'd write;</p>
<pre>    multi sub infix:~|_|~ (@data, Selector $is_sheep)</pre>
<p>[Update: This would now be spelled <code>infix:&lt;~|_|~&gt;</code>.]</p>
<pre>        is looser(&amp;infix:+)
        is assoc('non')
    {
        return part $is_sheep, @data;
    }</pre>
<p>Operators are often overloaded with multiple variants (as we'll <i><a href='#Arguments both ways'>soon see</a></i>), so we typically implement them as
multisubs. However, it's also perfectly possible to
implement them as regular subroutines, or even as macros.</p>
<p>To distinguish a binary operator from a regular multisub, we give
it a special compound name, composed of the keyword <code>infix:</code>
followed by the characters that make up the operator's symbol. These
characters can be any sequence of non-whitespace Unicode characters
(except left parenthesis, which can only appear if it's
the first character of the symbol). So, instead of <code>~|_|~</code>, we could
equally well have named our partitioning operator any of:</p>
<pre>    infix:E&lt;yen&gt;
    infix:E&lt;brvbar&gt;
    infix:^%#$!
    infix:&lt;-&gt;
    infix:E&lt;nabla&gt;</pre>
<p>The <code>infix:</code> keyword tells the compiler that the operator is placed between
its operands (as binary operators always are). If we're declaring a
unary operator, there are three other keywords that can be used instead:
<code>prefix:</code>, <code>postfix:</code>, or <code>circumfix:</code>. For example:</p>
<pre>    sub prefix:E&lt;plusmn&gt; (Num $n) is equiv(&amp;infix:+) { return +$n|-$n }

    sub postfix:E&lt;sup2&gt; (Num $n) is tighter(&amp;infix:**) { return $n**2 }

    sub circumfix:E&lt;lfloor&gt;...E&lt;rfloor&gt; (Num $n) { return POSIX::floor($n) }

    # and later...

    $error = E&lt;plusmn&gt;E&lt;lfloor&gt;$xE&lt;sup2&gt;E&lt;rfloor&gt;;</pre>
<p>The <code>is tighter</code>, <code>is looser</code>, and <code>is equiv</code> traits tell the parser
what the precedence of the new operator will be, relative to existing
operators. Namely, whether the operator binds more tightly than, less
tightly than, or with the same precedence as the operator named in the
trait. Every operator has to have a precedence and associativity, so
every operator definition has to include one of these three traits.</p>
<p>The <code>is assoc</code> trait is only required on infix operators and specifies
whether they chain to the left (like <code>+</code>), to the right (like <code>=</code>),
or not at all (like <code>..</code>). If the trait is not specified, the operator takes
its associativity from the operator that's specified in the <code>is tighter</code>,
<code>is looser</code>, or <code>is equiv</code> trait.</p>
<a name='Arguments both ways'></a><h2>Arguments both ways</h2>
<p>On the other hand, we might prefer that the selector come first (as it does in
<code>&amp;part</code>):</p>
<pre>    %parts = Animal::Cat ~|_|~ @animals;</pre>
<p>in which case we could just add:</p>
<pre>    multi sub infix:~|_|~ (Selector $is_sheep, @data)
        is equiv( &amp;infix:~|_|~(Array,Selector) )
    {
        return part $is_sheep, @data;
    }</pre>
<p>So now we can specify the selector and the data in <i>either</i> order.</p>
<p>Because the two variants of the <code>&amp;infix:~|_|~</code> multisubs have
different parameter lists (one is <code>(Array,Selector)</code>, the other is
<code>(Selector, Array)</code>, Perl 6 always knows which one to call. If the
left operand is a <code>Selector</code>, the <code>&amp;infix:~|_|~(Selector,Array)</code>
variant is called. If the left operand is an array, the
<code>&amp;infix:~|_|~(Array,Selector)</code> variant is invoked.</p>
<p>Note that, for this second variant, we specified <code>is equiv</code> instead of <code>is
tighter</code> or <code>is looser</code>. This ensures that the precedence and
associativity of the second variant are the same as those of the first.
That's also why we didn't need to specify an <code>is assoc</code>.</p>
<a name='Parting is such sweet sorrow'></a><h1>Parting is such sweet sorrow</h1>
<p>Phew. Talk about &quot;more than one way to do it&quot;!</p>
<p>But don't be put off by these myriads of new features and alternatives.
The vast majority of them are special-purpose, power-user techniques
that you may well never need to use or even know about.</p>
<p>For most of us it will be enough to know that we can now add a proper
parameter list, with sensibly named parameters, to any subroutine. So
that what we used to write as:</p>
<pre>    sub feed {
        my ($who, $how_much, @what) = @_;
        ...
    }</pre>
<p>we now write as:</p>
<pre>    sub feed ($who, $how_much, *@what) {
        ...
    }</pre>
<p>or, when we're feeling particularly cautious:</p>
<pre>    sub feed (Str $who, Num $how_much, Food *@what) {
        ...
    }</pre>
<p>And just being able to do that is a huge win for Perl 6.</p>
<a name='Parting shot'></a><h1>Parting shot</h1>
<p>By the way, here's (most of) that same partitioning functionality implemented
in Perl 5:</p>
<pre>    # Perl 5 code...
    sub part {
        my ($is_sheep, $maybe_flag_or_labels, $maybe_labels, @data) = @_;
        my ($sheep, $goats);
        if ($maybe_flag_or_labels eq &quot;labels&quot; &amp;&amp; ref $maybe_labels eq 'ARRAY') { 
            ($sheep, $goats) = @$maybe_labels;
        }
        elsif (ref $maybe_flag_or_labels eq 'ARRAY') {
            unshift @data, $maybe_labels;
            ($sheep, $goats) = @$maybe_flag_or_labels;
        }
        else {
            unshift @data, $maybe_flag_or_labels, $maybe_labels;
            ($sheep, $goats) = qw(sheep goats);
        }
        my $arg1_type = ref($is_sheep) || 'CLASS';
        my %herd;
        if ($arg1_type eq 'ARRAY') {
            for my $index (0..$#data) {
                my $datum = $data[$index];
                my $label = grep({$index==$_} @$is_sheep) ? $sheep : $goats;
                push @{$herd{$label}}, $datum;
            }
        }
        else {
            croak &quot;Invalid first argument to &amp;part&quot;
                unless $arg1_type =~ /^(Regexp|CODE|HASH|CLASS)$/;
            for (@data) {
                if (  $arg1_type eq 'Regexp' &amp;&amp; /$is_sheep/
                   || $arg1_type eq 'CODE'   &amp;&amp; $is_sheep-&gt;($_)
                   || $arg1_type eq 'HASH'   &amp;&amp; $is_sheep-&gt;{$_}
                   || UNIVERSAL::isa($_,$is_sheep)
                   ) {
                    push @{$herd{$sheep}}, $_;
                }
                else {
                    push @{$herd{$goats}}, $_;
                }
            }
        }
        return map {bless {key=&gt;$_,value=&gt;$herd{$_}},'Pair'} keys %herd;
    }</pre>
<p>Which is <i>precisely</i> why we're developing Perl 6.</p>
</div>
